[英]php - syntax error, unexpected '(', expecting ')'
I was developing a site using Laravel 4. I had this piece of code in one of my models: 我正在使用Laravel 4开发一个站点。在我的一个模型中有以下代码:
class MyModel extends Eloquent {
protected $var = array(
"label" => Lang::get("messages.label"),
"code" => "myCode",
);
...
}
But I gave this syntax error on the line where I used Lang::get
: 但是我在使用
Lang::get
的那一行上给出了这个语法错误:
syntax error, unexpected '(', expecting ')'
Then I changed my code into this: 然后我将代码更改为:
class MyModel extends Eloquent {
protected $var;
public function __construct() {
$this->var = array(
"label" => Lang::get("messages.label"),
"code" => "myCode",
);
}
}
And the error went gone! 错误消失了! I think the error is very confusing and unhelpful.
我认为该错误非常混乱且无济于事。 Why does php show this error message?
为什么php显示此错误消息?
It is because you use Lang::get()
when defining a class property, which is not allowed. 这是因为在定义类属性时使用了
Lang::get()
,这是不允许的。 Calling stuff like static methods can only be done at runtime (when the code is being executed). 只能在运行时 (执行代码时)执行诸如静态方法之类的调用。
When you define classes their properties can only be non-variable (or "constant") values (such as integers, strings or arrays that themselves only contain non-variable values). 当定义类时,它们的属性只能是非变量(或“常数”)值(例如本身仅包含非变量值的整数,字符串或数组)。
Runtime code should be put into the constructor. 运行时代码应放入构造函数中。
The issue is because you're calling Lang::get which is a function when initializing your class attribute, and default values for class attributes can only be constant values. 问题是因为您在初始化类属性时调用的是Lang :: get函数,而类属性的默认值只能是常量值。
You're correct to initialise these attributes in the constructor instead. 您正确地在构造函数中初始化这些属性是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.