Creating Anonymous PHP Objects

>> Saturday, February 19, 2011

So I'm working on akaikiwi and found out a very nice thing, which doesn't really help me right now, but I really feel like sharing it, as I'm sure it'll be useful for somebody.

$obj = (object) array('foo' => 'bar', 'property' => 'value');
echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

That's it! That will cast the associative array to stdObject. Useful to save some code.
In PHP 5.3 you could actually also use closures to make some nasty stuff, it's a pity PHP 5.3 is still not widely used.

Source: http://www.php.net/manual/en/language.oop5.php#84292

Post a Comment

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP