July 2010
Casting arrays as objects (and vice-versa) in PHP
I just learned that it's possible to cast an associative array as an object in PHP.
It works the other way, too—an object can be cast as an array.
This is especially useful when working with the results of database queries. A lot of codebases seem unsure whether to treat database rows as arrays, or as objects. In these environments, it's likely that you'll get one type as the return value from a particular method, but need to pass the other type as an argument to a second method.
So it's nice to have a simple and language-native way to convert between the two. Some simple demo code:
<?php // create an array $array = array( 'prop1' => 'value1', 'prop2' => 'value2' ); // cast it to an object $object = (object) $array; echo 'The value of the property prop1 is: ' . $object->prop1 . '<br />'; echo 'The value of the property prop2 is: ' . $object->prop2 . '<br />'; // cast it back to an array $array2 = (array) $object; echo 'The value for the key prop1 is: ' . $array2['prop1'] . '<br />'; echo 'The value for the key prop2 is: ' . $array2['prop2'] . '<br />'; ?>
Peter Michaux
Douglas Crockford's articles on JavaScript (and his posts at the Yahoo! User Interface Blog) have helped me greatly to understand the more exotic and subtle features of the language, along with the patterns that exploit those features.
Now I've discovered a similar collection of articles by Peter Michaux. They often riff on Crockford's ideas, sometimes offering a fresh perspective and sometimes explaining things in a more accessible way. Well worth a read for aspiring JavaScript ninjas.