在另一个属性中访问一个对象属性

问题描述:

当我尝试执行以下操作时,我得到一个syntax error, unexpected T_VARIABLE。我究竟做错了什么?在另一个属性中访问一个对象属性

class myObj { 
    public $birth_month; 
    public $birthday = array('input_val' => $this->birth_month); 
} 

我也试过

class myObj { 
    public $birth_month; 
    public $birthday = array('input_val' => $birth_month); 
} 

您不能使用表达式来初始化类属性。它必须是一个常量值,或者你必须在构造函数中初始化它。这是你的语法错误的来源。

class myObj { 
    public $birth_month; 
    public $birthday; 

    // Initialize it in the constructor 
    public function __construct($birth_month) { 
    $this->birth_month = $birth_month; 
    $this->birthday = array('input_val' => $this->birth_month); 
    } 
} 

From the docs on class properties:

他们通过使用关键字公有,保护或私有,其次是普通变量声明的一个定义。这个声明可能包括一个初始化,但是这个初始化必须是一个常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖运行时信息来进行评估。

在你的第一次尝试,使用$this实例方法外不会被支持,即使霸菱属性初始化的编译时间的限制,因为$this只是实例方法里面有意义。

$这并不类的非静态方法之外存在。另外,在初始化时,还没有$。在构造函数方法中初始化您的数组。