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)
* }
*/
8 comments
Comments feed for this article
Trackback link
http://www.otton.org/2008/08/14/neat-php-tricks-casting-arrays-to-objects/trackback/
September 6, 2008 at 4:50 am
Pingback from [PHP] 將 array 強制轉型為 object « Oceanic | 人生海海
October 19, 2008 at 6:19 am
Pingback from Recent Links Tagged With “arrays” - JabberTags
August 15, 2008 at 8:54 am
Ivan Iordanov
Why not to use $obj = new ArrayObject($array);
August 15, 2008 at 10:39 am
david
Well,
ArrayObjectdoes get you neat stuff likeTraversableandCountable, but if you don’t need them, casting tostdClassis roughly twice as fast.August 15, 2008 at 2:55 pm
Jonathan Franzone
Nice tip! I didn’t actually know you could just do a cast like that.
August 15, 2008 at 2:56 pm
Dave
What about multi-dimensional arrays?
August 15, 2008 at 3:41 pm
Erick
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
August 15, 2008 at 3:48 pm
david
Erick: $obj is still an object when you reach the loop. Try this:
$obj = (array)$obj;
var_dump($obj);
(love your site design, BTW).