为避免收到上一个问题中的错误消息,我决定使用__get()
如下所示更改类,
class property
{
public function __get($name)
{
return isset($this->$name) ? $this->$name : new property;
}
}
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 = null;
$type = $object->array_to_object($type,true);
var_dump($type->a->b->c);
所以我最终得到了这个结果,
object(property)#3 (0) { }
但它仍然不完美。据我了解,上述解决方案像这样处理链中的对象,
$type = object{}->object{}->object{}
所以我想知道我是否可以找到它是否是最后一个链并且它是空的然后只输出一个null
?
$type = object{}->object{}->NULL
PHP可以吗?
编辑:
我想到了一个想法,就是计算属性类被实例化了多少次,
class property
{
public static $counter = 0;
function __construct() {
self::$counter++;
}
public function __get($name)
{
if(isset($this->$name))
{
return $this->$name;
}
elseif(property::$counter < 3)
{
return new property;
}
else
{
return null;
}
}
}
但我唯一的问题是如何使数字3
动态化。有任何想法吗?