2
votes

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?

2

2 Answers

3
votes

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.

1
votes

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.