syntax error, unexpected '(', expecting ')'

I was developing a site using Laravel 4. I had this piece of code in one of my models:

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 :

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?


It is because you use Lang::get() when defining a class property, which is not allowed. 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.

You're correct to initialise these attributes in the constructor instead.

链接地址: http://www.djcxy.com/p/9964.html

上一篇: 创建对象时的反斜杠语法

下一篇: 语法错误,意外'(',期待')'