试试这个:
$test = array (2+2);
var_dump($test);
然后尝试相同但在课堂内:
class test {
public $test = array(2+2);
}
我只想知道为什么会出现一个解析器错误,并且可能如何解决这个问题(在一个类中)尽可能的代码友好和高效。
答案 0 :(得分:5)
您无法使用语句初始化类字段。它必须是文字,恒定的价值。解决方法是使用构造函数:
class Test {
public $test;
public function __construct() {
$this->test = array(2+2);
}
}
来自 the manual:
类成员变量称为“属性”。你也可以看到它们 引用使用其他术语,如“属性”或“字段”,但 出于本参考的目的,我们将使用“属性”。他们是 使用其中一个关键字
public
,protected
或private
进行定义, 然后是正常的变量声明。 此声明可能 包括初始化,但这个初始化必须是一个常量 value - 也就是说,它必须能够在编译时进行评估 不得依赖于运行时信息才能进行评估。
答案 1 :(得分:1)
原因是因为类中属性的赋值必须是静态声明。它们不能是被评估的表达式。
你可以这样做:
public $test = array(4); // static assignment
public $test = 'some string'; // static assignment
public $test = strtoupper(' some string '); // invalid, expression
public $test = $global_variable; // invalid, not a constant expression
public $test = time(); // invalid, an expression