Neat PHP Tricks: Casting Arrays to Objects

Array notation is fine, but it can look a bit clunky when you’re working with complex structures. This is a fairly simple example, but I’m sure we’ve all dealt with worse:

 
$clientChanges['deletes'][$val['fkClient']] = $val['Total'];

Casting the array to an object allows us to use object notation (->) and makes the code more readable:

 
$val = (object) $val;
$clientChanges = (object) $clientChanges;
 
$clientChanges->deletes[$val->fkClient] = $val->Total;

You can even get away with using array functions on objects, as long as they’re just simple collections of properties:

 
$o3 = (object) array_merge( (array) $o1, (array) $o2 );

Of course, member functions won’t make it through this kind of mangling, but bizarrely, private variables do:

 
class O
{
    private $a = 4;
    var $b = 5;
    var $c = 6;
}
 
$o = new O();
 
$o = ( object ) array_reverse( ( array )$o );
 
var_dump( $o );
 
/**
 * outputs:
 *
 * object(stdClass)#2 (3) {
 *     ["c"]=> int(6)
 *     ["b"]=> int(5)
 *     ["a:private"]=> int(4)
 * }
 */

Tags: ,

  1. Ivan Iordanov’s avatar

    Why not to use $obj = new ArrayObject($array);

  2. david’s avatar

    Well, ArrayObject does get you neat stuff like Traversable and Countable, but if you don’t need them, casting to stdClass is roughly twice as fast.

  3. Jonathan Franzone’s avatar

    Nice tip! I didn’t actually know you could just do a cast like that.

  4. Dave’s avatar

    What about multi-dimensional arrays?

  5. Erick’s avatar

    It seems that the private variable is there in the array yes but it seems that it is invisible.

    Try this:
    class obj
    {
    public $var1 = 1;
    public $var2 = 2;
    private $var3 = 3;
    }

    $obj = new obj();

    var_dump((array)$obj);

    foreach($obj as $i)
    echo $i;

    It will ouput:
    array(3) {
    ["var1"]=>
    int(1)
    ["var2"]=>
    int(2)
    ["�obj�var3"]=>
    int(3)
    }
    12

  6. david’s avatar

    Erick: $obj is still an object when you reach the loop. Try this:


    $obj = (array)$obj;
    var_dump($obj);

    (love your site design, BTW).