我stdClass
用来将数组转换为对象,
function array_to_object($array)
{
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
foreach($array as $key => $value)
{
$key = (string) $key ;
$object->$key = is_array($value) ? array_to_object($value) : $value;
}
return $object;
}
$type = array(
"category" => "admin",
"person" => "unique"
);
$type = array_to_object($type);
var_dump($type->category); // string(5) "admin"
当然,当我想首先获取未在数组中设置的属性时会出错,
var_dump($type->image);
错误信息,
Notice: Undefined property: stdClass::$image in C:\wamp\www\test\2012\php\array_to_object.php on line 52
NULL
null
我想知道如果没有找到属性,我是否可以让函数返回?
var_dump($type->image); //NULL
编辑:
决定把上面的那个函数变成一个类,但还是不能__get()
正常工作,
class objectify
{
public function __get($name)
{
if (isset($this->$name) === true){
return $this->$name;
} else {
return null;
}
}
public function array_to_object($array)
{
if(!is_array($array)) {
return $array;
}
$object = self::__get($name);
foreach($array as $key => $value)
{
$key = (string) $key ;
$object->$key = is_array($value) ? self::array_to_object($value) : $value;
}
return $object;
}
}
$object = new objectify();
$type = array(
"category" => "admin",
"person" => "unique"
);
$type = $object->array_to_object($type);
var_dump($type->category);
var_dump($type->image);
错误信息,
Notice: Undefined variable: name in C:\wamp\www\test\2012\php\array_to_object.php on line 85
string(5) "admin"
Notice: Undefined property: stdClass::$image in C:\wamp\www\test\2012\php\array_to_object.php on line 107
NULL
我认为这条线是错误的来源,但我不知道如何处理它......
$object = self::__get($name);