I have an array with approximately 50 keys & values. I would like to take the array and create class properties from the values like so:
$arr = array();
$arr['name'] = 'John';
$arr['age'] = '20';
$object = (object) $arr;
echo $object->name;
My question is, is this very resource-intensive? Would it require a lot of overhead with a large array? If so, would there be a better way of doing this?
Also, this does not work if the array is setup like:
$arr = array();
$arr['name']['boy'] = 'John';
$arr['name']['girl'] = 'Jane';
$arr['age']['boy'] = '20';
$arr['age']['girl'] = '30';
$object = (object) $arr;
echo $object->name->boy;
You can make like this :
$arr = array();
$arr['name']['boy'] = 'John';
$arr['name']['girl'] = 'Jane';
$arr['age']['boy'] = '20';
$arr['age']['girl'] = '30';
$obj = json_decode(json_encode($arr)); //Turn it into an object
print_r($obj); // to view the result
echo $obj->name->boy; // output: John
It works great with simple arrays and with subarrays too.
I think this is good solution when we work with subarrays and we want to save resources
According to the documentation an object of type stdClass is created. My guess is, that copy-on-write will not work. A short experiment with memory_get_usage()
showed the following results (three different scripts):
$arr=range(10,10000); $obj = $arr; var_dump(memory_get_usage()); // int(1717424)
$obj=(object)range(10,10000); var_dump(memory_get_usage()); // int(1717528)
$arr=range(10,10000); $obj = (object)$arr; var_dump(memory_get_usage());// int(2728048)
So you certainly use much more memory. If you want to reduce resources, something like this should work:
$object = (object)array('name' => 'John');
A better way could be to start with an object from the beginning:
$arr = new ArrayObject(array(), ArrayObject::STD_PROP_LIST);
Although you will have the same problem with nested arrays. If you know the structure of your array, try to extend ArrayObject
. Or you can write your own offsetSet()
method to implement the desired behavior. Take a look at ArrayAccess.