Sometimes I use __get
or stdClass
to convert arrays to object. But I can't decide I should stick to. I wonder which one is better and faster, any ideas?
class property
{
public function __get($name)
{
return (isset($this->$name)) ? $this->$name : null;
}
}
$object = new property();
$object = new stdClass();
so if I use new property()
, I will have a property object output,
property Object
(
....
)
while if I use new stdClass()
, I will have a stdClass object output,
stdClass Object
(
....
)
so I can get the object data like this $item->title
.
EDIT:
how I do the actual array to object conversion.
public function array_to_object($array = array(), $property_overloading = false)
{
# If $array is not an array, let's make it array with one value of former $array.
if (!is_array($array)) return $array;
# Use property overloading to handle inaccessible properties, if overloading is set to be true.
# Else use std object.
if($property_overloading === true) $object = new property();
else $object = new stdClass();
foreach($array as $key => $value)
{
$key = (string) $key ;
$object->$key = is_array($value) ? self::array_to_object($value, $property_overloading) : $value;
}
return $object;
}