gpt4 book ai didi

php - 如果未找到类中的属性,如何在函数/方法中返回 null?

转载 作者:行者123 更新时间:2023-12-02 00:22:12 24 4
gpt4 key购买 nike

我用 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);

最佳答案

将约翰关于 __get() 的回答放在一起:

<? //PHP 5.3+

class maybeBag {
public function __get($name){
if (isset($this->$name) === true){
return $this->$name;
} else {
return null;
}
}

public static function ensureIsObject($values){
if (\is_array($values) !== true){
return $values;
}
$o = new static(); //Late-bound make instance of own class
foreach($values as $key => $value){
$o->$key = static::ensureIsObject($value);
}
return $o;
}
}

//Demo

$type = array(
'category' => 'admin',
'person' => 'unique'
);
$type = maybeBag::ensureIsObject($type);

var_dump($type->category); //string(5) "admin"
var_dump($type->image); //NULL

?>

关于php - 如果未找到类中的属性,如何在函数/方法中返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10423792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com