您不能使用表达式来初始化类属性。这两个变量的值直到运行时才知道,因此不能在声明中使用。相反,在构造函数中定义它们。
public $head = array
(
// The title as a string literal is ok...
"title" => "blah",
"meta_title" => NULL,
"meta_content" => NULL
);
// Pass them to the constructor as parameters
public function __construct($meta_title, $meta_content)
{
// Initialize them in the constructor.
$this->head['meta_title'] = $meta_title;
$this->head['meta_content'] = $meta_content;
}
从文档
类成员变量称为“属性”。您可能还会看到使用“属性”或“字段”等其他术语来提及它们,但出于本参考的目的,我们将使用“属性”。它们是通过使用关键字 public、protected 或 private 之一定义的,后跟一个普通的变量声明。这个声明可能包括一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖于运行时信息才能被评估。