gpt4 book ai didi

php - 为什么 isset() 总是在自定义对象上返回 FALSE

转载 作者:可可西里 更新时间:2023-10-31 23:58:52 28 4
gpt4 key购买 nike

我无法理解这种行为:我的 isset() 检查总是在具有确定值的 property 上返回 false!

<?php

class User {
protected $userId; // always filled
protected $userName; // always filled

/**
* Magic method for the getters.
*
* @param type $property
* @return \self|property
*/
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
} else {
throw new Exception('property '.$property.' does not exist in '.__CLASS__.' class');
}
}

}

?>

当我使用以下代码从另一个类检查此变量时:

isset($loggedUser->userName); // loggedUser is my instantiation of the User.php

它返回FALSE??但是当我在我的 User.php 中重载 __isset() 函数时,我得到了 TRUE ,正如我预期的那样:

public function __isset($name)
{
return isset($this->$name);
}

明确一点:

echo $loggedUser->name;   // result "Adis"
isset($loggedUser->name); // results in FALSE, but why?

感谢您的帮助!

最佳答案

protected 属性仅在对象的方法中可见。它们对外部访问是隐藏的。


class prot_text {
protected $cannot_see_me;
function see_me() {
echo $this->cannot_see_me;
}
}

$x = new prot_text();
echo $x->cannot_see_me; // does not work - accessing from "outside"
$x->see_me(); // works, accessing the attribute from "inside".

关于php - 为什么 isset() 总是在自定义对象上返回 FALSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899547/

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