Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 访问另一个属性中的一个对象属性_Php_Attributes - Fatal编程技术网

Php 访问另一个属性中的一个对象属性

Php 访问另一个属性中的一个对象属性,php,attributes,Php,Attributes,当我尝试执行以下操作时,我得到一个语法错误,意外的T\u变量。我做错了什么 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);

当我尝试执行以下操作时,我得到一个
语法错误,意外的T\u变量
。我做错了什么

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);
}

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

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

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);
  }
}

它们是通过使用关键字public、protected或private中的一个来定义的,后跟一个普通变量声明。该声明可能包含一个初始化,但该初始化必须是一个常量值——也就是说,它必须能够在编译时进行计算,并且必须不依赖于运行时信息才能进行计算

在您的第一次尝试中,在实例方法之外使用
$this
,即使没有属性初始化的编译时限制,也不受支持,因为
$this
仅在实例方法内部有意义