从另一个类调用变量,作用域有问题


Calling a variable from another class, issues with scope

好的,我已经缩小了我的问题范围,但无法提出解决方案。

我希望第一个类能够引用第二个类中的变量。

class TheFirstClass{
    public function __construct(){
        include 'SecondClass.php';
        $SecondClass = new SecondClass;
        echo($SecondClass->hour);
    }
}
//in it's own file
class TheSecondClass{
    public $second;
    public $minute = 60;
    public $hour;
    public $day;
    function __construct(){ 
        $second = 1;
        $minute = ($second * 60);
        $hour = ($minute * 60);
        $day = ($hour * 24);
    } 
}

但在这种情况下,只能从另一个类访问"分钟"。如果我删除"= 60",那么分钟将不返回任何内容以及其余变量。

构造函数中的变量计算正确,但它们不会影响作用域中较高名称的变量。为什么,构建代码的正确方法是什么?

引用带有$this->前缀的属性:

    $this->second = 1;
    $this->minute = ($this->second * 60);
    $this->hour = ($this->minute * 60);
    $this->day = ($this->hour * 24);

不使用$this->创建仅存在于局部范围中的新局部变量,不会影响属性。

您使用的变量仅在__construct函数内部使用。您必须使用对象变量才能在其他类中看到它们

function __construct(){ 
    $this->second = 1;
    $this->minute = ($this->second * 60);
    $this->hour = ($this->minute * 60);
    $this->day = ($this->hour * 24);
} 

稍后编辑:请注意,您不必在第二个类的构造函数中使用include函数。你可以有这样的东西:

<?php
  include('path/to/my_first_class.class.php');
  include('path/to/my_second_class.class.php');
  $myFirstObject = new my_first_class();
  $mySecondObject = new my_second_class();
?>