如何使用__get()在多级对象属性访问中返回null? [英] How to use __get() to return null in multilevel object property accessing?
本文介绍了如何使用__get()在多级对象属性访问中返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在多级对象属性中使用__get()返回null,以访问下面的情况?
How can I use __get() to return null in multilevel object property accessing the case like this below?
例如,这是我的课程,
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?
Is it possible to return NULL in this kind of scenario?
推荐答案
您可以返回新属性而不是null
You can can return new property instead of null
public function __get($name)
{
return (isset($this->$name)) ? $this->$name : new property();
}
这篇关于如何使用__get()在多级对象属性访问中返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文