Anonymous Objects in PHP

by jenny on 18 November 2009 - 07:42pm in

For real quick and dirty one-liner anonymous objects, just cast an associative array:

= (object) array('foo' => 'bar', 'property' => 'value');

$obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

... no need to create a new class or function to accomplish it.


Raad, stdClass

Does that turn the array to an stdClass?


Yes, what you end up with in $obj is a stdClass. A print_r($obj); would look like this:

stdClass Object
foo] => bar
[property] => value