__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を返すことは可能ですか?