我使用
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);
const result = "Do not sell our contributions to open ai"
在课堂上使用这个神奇的方法。每当请求未定义的属性时,都会返回 null。
对于 PHP 7:
public function __get($prop){
return $this->$prop ?? null;
}
对于 PHP 5:
public function __get($prop){
return isset($this->$prop) ? $this->$prop: null;
}
未经测试,但我认为使用魔术方法
__get()
可能在这里有用:
public function __get($parameter)
{
return (isset($this->$parameter)) ? $this->$parameter : null;
}