我遇到了一个奇怪的错误。你可能会说:"为什么奇怪呢?你只是没有这个属性而已。" 不,问题就在于有 这个 属性。
我在这里遇到了一个错误。
// PHP Notice: Undefined property: stdClass::$roles in
$canWrite = $this->session->isLoggedIn() ? $this->page->canWrite($this->session->user->roles) : false;
这是一个类。
class User {
protected $roles;
function getRoles() {
if (!$this->roles)
{
// Get them!
}
return $this->roles;
}
}
当我尝试在这一行访问属性时,就会调用这个方法。一切都运行良好,但我不想增加我的错误日志。发生了什么?
更新1
$this->user->session
是一个 User
对象。
function getUser() {
if (!$this->user) {
$u = new User();
// Logic
$this->user = $u;
}
return $this->user;
}
User Object
(
[roleId:protected] => 1
[roles:protected] => Array
(
[root] => Role Object
(
[id:protected] => 1
[hrefname:protected] => root
)
)
)
更新2
所有属性均通过魔术方法__get()
访问。
public function __get($var) {
if ($this->__isset($var)) {
$method = 'get'.ucfirst($var);
if (method_exists($this, $method)) {
return $this->$method();
} else {
return $this->$var;
}
}
throw new Exception("Unrecognized attribute '$name'");
}
UPD3
var_dump($this->session->user)
object(User)#370 (30) {
["roles":protected]=>
array(1) {
["root"]=>
object(Role)#372 (2) {
["id":protected]=>
string(1) "1"
["hrefname":protected]=>
string(4) "root"
}
}
}
解释
我在一个地方错误地写成了$this->session->user->id = $user->id
,而此时$this->session->user
还未被创建。因此,null->id
实际上是(new stdClass())->id
。好吧,感谢PHP。
$this->session->user
不是一个User
对象。它是一个通用的stdClass
对象,没有$roles
属性。请发布设置$this->session->user
的代码... - Michael Berkowski$this->session->user
是如何创建的?PHP 将其识别为stdClass
对象,而不是User
对象。 - CatUser::$roles
是protected
的,所以您无法通过$something->user->roles
公开访问它。这就是User::getRoles()
方法的作用。 - Michael Berkowskiunset
引起的。我误将属性进行了“unset” 而不是清空它们... - Buksy