Typecast property as an object

Is it possible to specify a property as an object when creating properties? For example, the $ array is valid, however my two attempts to do this with an object are not.

thanks

class xxx { public $array=array(), $object1=new stdClass(), $object2=object() } 
+4
source share
2 answers

No, PHP does not allow you to do this. the only way to assign an object to a class property is through class methods.

if you want an empty class to be assigned to a class property when initializing the object, you can use this constructor method.

 class xxx { public $array = array(); public $object1; public function __construct() { $this->object1 = new stdClass(); } } 
+4
source

This is not possible because class definitions are executed at the time of compiling PHP. Expressions are not translated at this time. This means that only direct assignments such as strings, float, ints and arrays are allowed.

See Runtime and compilation time.

0
source

Source: https://habr.com/ru/post/1412775/


All Articles