PHP对象生存期

PHP对象生存期,php,function,object,scope,Php,Function,Object,Scope,一旦我的文件开始运行100多行,我就开始考虑将它们拆分为功能部分。然后我遇到了一个问题,下面的简化代码给出了这个问题。我知道HTTP是无状态的,除非存储到会话或数据库中,否则对象和变量无法保存到另一个脚本中。我感到困惑的是为什么它不能这样工作 <?php class Student{ public $name; public $age; } function do_first(){ $student1 = new Student();

一旦我的文件开始运行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();

 ?>

函数中定义的变量在该函数的范围内

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

$student1 = new Student();

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

do_first($student1);
或:

使用全局关键字(我认为这很可怕)


变量在另一个作用域中定义。
$student1 = new Student();

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

do_first($student1);
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
}