有时我使用__get
orstdClass
将数组转换为 object。但我不能决定我应该坚持下去。我想知道哪个更好更快,有什么想法吗?
class property
{
public function __get($name)
{
return (isset($this->$name)) ? $this->$name : null;
}
}
$object = new property();
$object = new stdClass();
所以如果我使用new property()
,我将有一个属性对象输出,
property Object
(
....
)
而如果我使用new stdClass()
,我将有一个stdClass 对象输出,
stdClass Object
(
....
)
所以我可以像这样得到对象数据$item->title
。
编辑:
我如何进行实际的数组到对象的转换。
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;
}