PHP对象生存期

时间:2014-07-16 22:41:02

标签: php function object scope

一旦我的文件开始超过100行,我就开始考虑将它们分成功能部分。然后我遇到了一个问题,在下面的简化代码中给出了。我知道HTTP是无状态的,除非存储在会话或数据库中,否则对象和变量不会存在于另一个脚本中。我感到困惑的是为什么它不会这样工作?

 <?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-&gt; age; 行中收到错误说:

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

1 个答案:

答案 0 :(得分:1)

函数中定义的变量属于该函数的范围。的范围

您需要在全局范围内定义学生并将其作为参数传递:

$student1 = new Student();

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

do_first($student1);

使用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
}