0

Basically what I want to do is this

class A {

    public $prop = new stdClass;

}

And PHP is telling me I can't do this:

PHP Parse error: syntax error, unexpected 'new' (T_NEW) in - on line ##

What's up with that? I know that you basically can't assign a function's return value to a property in initialization, but can someone explain why is that, like the technical stuff. Thanks in advance!

0

2 Answers 2

2

Try to use class constructor:

class A {

    public $prop;

    public function __construct(){

        $this->prop = new stdClass;

    }

}

PHP manual says:

Declaration of properties may include an initialization, but this initialization must be a constant value - that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

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

2 Comments

But how is an empty stdClass not a constant?
PHP doesn't check what you're trying to instantiate. in this case, it's just parsing the code and sees you're trying to use a dynamic available-at-execution-time-only code structure and bails out. Doesn't matter if stdclass is "empty" right now anyways. In the future it may not be.
1

class variables must be initialized with static values, e.g.

public $prop = 7; // ok
public $prop = 7+7; // ok - can be evaluated at compile time
public $prop = new stdClass; // bad, dynamic result.
public $prop = get_some_value(); //also bad, dynamic result not available at compile time

2 Comments

Well yeah, I came to that conclusion. I'm actually asking what's causing that.
It's a PHP restriction. The only way to get around it is to define the class variables with null/default fixed values, and then assign the dynamic stuff in the constructor.

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.