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;
}
First off, an (almost) empty class definition like you have is almost like an
stdClassso there won’t be any major issues by using either.That said, one advantage your “named” class has over
stdClassis that you can define what happens when a non-existent property is being accessed by taking advantage of the__getmagic method.The above is a simpler rewrite of your original
propertyclass; when__get()is being called, you already know that$this->$nameis not set. Although this won’t cause a notice, it doesn’t prevent a fatal error when you try to reference$obj->bla->blawhere$obj->bladoesn’t exist.It might be more useful to throw an exception when a non-existent property is being accessed:
This allows your code to catch the exception before it turns into a fatal runtime error that stops your script altogether.