如何使用 __get() 在访问下面这样的案例的多级对象属性中返回 null?
例如,这是我的课,
class property
{
public function __get($name)
{
return (isset($this->$name)) ? $this->$name : null;
}
}
class objectify
{
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)) $array = array($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;
}
}
我如何使用它,
$object = new objectify();
$type = array(
"category" => "admin",
"person" => "unique",
"a" => array(
"aa" => "xx",
"bb"=> "yy"
),
"passcode" => false
);
$type = $object->array_to_object($type,true);
var_dump($type->a->cc);
结果,
null
但是当输入数组为 NULL 时,我收到一条错误消息null
,
$type = null;
$type = $object->array_to_object($type,true);
var_dump($type->a->cc);
结果,
Notice: Trying to get property of non-object in C:\wamp\www\test...p on line 68
NULL
在这种情况下可以返回 NULL 吗?