如何使用__get()在多級別對象屬性中返回null,以訪問如下所示的情況?如何使用__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
,
$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?
PHP語言不知道多級對象,對象始終是一個單一的節點,它在上下文中訪問時對升序或降序節點一無所知。 – hakre