4

Is it possible to typecast a property as an object when defining the properties? For instance, $array is valid, however, my two attempts of doing so with an object are not.

Thank you

class xxx
{
    public  $array=array(),
            $object1=new stdClass(),
            $object2=object()
}
user1032531
  • 24,767
  • 68
  • 217
  • 387

2 Answers2

4

No, PHP does not allow you to do that. the only way you can assign an object to class property is via class methods.

if you want an empty class to be assigned to class property upon object initialization then you can do this trough constructor method.

class xxx {
    public $array = array();
    public $object1;

    public function __construct() {
        $this->object1 = new stdClass();
    }
}
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
0

That's not possible, because class definitions are executed in the compile time of PHP. At this time no expressions are translated. That means only direct assignments like strings, floats, ints and arrays are allowed.

See Runtime vs compile time

Community
  • 1
  • 1
dan-lee
  • 14,365
  • 5
  • 52
  • 77