Avoiding temporary array assignment in PHP

Even though I’ve been developing with PHP for a number of years, I still enjoy discovering new ways of working. Even though the stdClass object is about as basic as you can get, it’s never struck me as being a worthwhile tool. Today, I was storing an associative array of objects in a Zend_Registry. Because PHP’s syntax does not support array accessors on method calls, I had to perform a temporary assignation, as follows:

$arrayOfObjects = Zend_Registry::get('stuff');
$object = $arrayOfObjects['key'];
$object->foo();
// of course, I could do:
// $arrayOfObjects['key']->foo();
// but I still need the temporary assignment

Because I decided to put a stdClass object into the Zend_Registry, the code reads a little more fluently:

Zend_Registry::get('stuff')->key->foo();

As far as I’m aware, there is no significant penalty for using stdClass, but the results are much nicer.

Tags: , ,

Leave a Reply