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 ...
變量在另一個範圍內定義。 http://php.net/manual/en/language.variables.scope.php – zerkms