2014-07-16 136 views
0

一旦我的文件開始執行超過100行,我開始考慮將它們分解爲功能部分。然後我遇到了一個問題,這個問題在下面的簡化代碼中介紹。我知道HTTP是無狀態的,對象和變量不會存活到另一個腳本中,除非存儲在會話或數據庫中。我很困惑的是爲什麼它不會這樣工作?PHP對象生命週期

<?php 

class Student{ 

    public $name; 
    public $age; 
} 

function do_first(){ 

    $student1 = new Student(); 
    $student1->name = "Michael"; 
    $student1->age = 21; 
    echo $student1->name . "</br>"; 
} 

function do_second(){ 
    echo $student1->age; 
} 

do_first(); 
do_second(); 

?> 

我在處得到一個錯誤echo $ student1-> age;線說:在一個函數定義

Undefined variable: student1 ... Trying to get property of non-object ... 
+1

變量在另一個範圍內定義。 http://php.net/manual/en/language.variables.scope.php – zerkms

回答

1

變量是功能範圍內

您需要在全局範圍內定義的學生,在把它作爲一個參數:

$student1 = new Student(); 

function do_first(Student $student) { 
    $student->name = 'Michael'; 
} 

do_first($student1); 

OR:

使用global關鍵字(這是可怕的,我認爲)

function do_first() { 
    global $student1; // Pull $student1 from the global scope 
    $student1 = new Student(); 
    // ... 
} 

function do_second { 
    global $student1; // Pull $student1 from the global scope 
}