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)
* }
*/
-
What about multi-dimensional arrays?
-
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 -
Pingback from [PHP] 將 array 強制轉型為 object « Oceanic | 人生海海 on September 6, 2008 at 4:50 am
-
Pingback from [PHP] ? array ????? object - My Habari on January 28, 2009 at 5:16 pm
9 comments
Comments feed for this article
Trackback link: http://www.otton.org/2008/08/14/neat-php-tricks-casting-arrays-to-objects/trackback/