I want to set attribute for a stdClass object in a single statement.
I don’t have any idea about it. I know the following things
$obj = new stdClass;
$obj->attr = 'loremipsum';
It takes two statements.
$obj = (object) array('attr'=>'loremipsum');
It takes single statement but it is not direct method.
$obj = new stdClass(array('attr'=>'loremipsum'));
It is not working.
Actually, that’s as direct as it’s going to get. Even a custom constructor won’t be able to do this in a single expression.
The
(object)cast might actually be a simple translation from an array, because internally the properties are stored in a hash as well.You could create a base class like this:
Doing so will lock up your constructor though, requiring each class to call its parent constructor when overridden.