0

I have a class with typed property object. I need to define default empty value for that property:

This doesn't work:

public object $doctor = new \stdClass();

Is this even possible?

3
  • 1
    "This declaration may include an initialization, but this initialization must be a constant value" From the Docs. Commented Feb 9, 2021 at 17:05
  • 1
    Either set it in constructor or in __get(). Or possible check it and instantiate it when needed to use it. Commented Feb 9, 2021 at 17:23
  • 1
    From the docs: "Typed properties must be initialized before accessing, otherwise an Error is thrown." Commented Feb 9, 2021 at 17:38

2 Answers 2

2

This is impossible and the error you get (Constant expression contains invalid operations) explains why: in PHP the properties can only be initialized with constant expressions. You can't use any function calls, variables or an expression producing a new object instance like in your case.

See more details here: PHP Error : Fatal error: Constant expression contains invalid operations

As a workaround I'd suggest initializing the property in the constructor

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

Comments

1

Just declare a new class instance and fill $ obj = new stdClass ();

public object $doctor = new stdClass();

$doctor->name="namedoctor"

$doctor->titles= array('doc', 'specialist');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.