2

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?

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This might be the fricking least explaining error message in PHP I have ever come accross to show in this case. Man, I was banging my head against the wall.
@morksinaanab Yeah, you have to know how PHP works in order to understand the error, and even then it is not really that apparent. Error messages have been improved somewhat in newer versions of PHP, though.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.