Marc DePoe
Marc DePoe

Reputation: 43

Is there a way to "cast" an array to (object) as a property of class/trait?

In PHP, I like the ability to declare objects (new instances of the stdClass) in one step like so:

$obj = (object) ['a','b','c'];

This works great.. but as a class property:

class Foo {
    public $obj = (object) ['a','b','c'];
}

I get the following error:

syntax error, unexpected '(object)' (object) (T_OBJECT_CAST)

Is there another way to accomplish this? And, does anyone know why the above code is disallowed (perhaps specific to php 5.6)? I couldn't find specific documentation anywhere.

Upvotes: 0

Views: 756

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

Quoting from the PHP Docs:

They [object properties] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration 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.

(my emphasis)

And

public $obj = (object) ['a','b','c'];

is dependent on run-time information, namely run-time casting of array to object

The way to get round this is to assign the value in the constructor

Upvotes: 3

Related Questions