我收到了这个奇怪的错误.你会说:"为什么这么奇怪?你只是没有这样的财产".首要问题是存在的财产.
我在那里得到一个错误.
// PHP Notice: Undefined property: stdClass::$roles in
$canWrite = $this->session->isLoggedIn() ? $this->page->canWrite($this->session->user->roles) : false;
Run Code Online (Sandbox Code Playgroud)
这是班级.
class User {
protected $roles;
function getRoles() {
if (!$this->roles)
{
// Get them!
}
return $this->roles;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试访问此行中的属性时,将调用此方法.一切正常但我不想增加我的错误日志.发生了什么?
$this->user->session是一个User对象
function getUser() {
if (!$this->user) {
$u = new User();
// Logic
$this->user = $u;
}
return $this->user;
}
Run Code Online (Sandbox Code Playgroud)
User Object
(
[roleId:protected] => 1
[roles:protected] => Array
(
[root] => Role Object
(
[id:protected] => 1
[hrefname:protected] => root
)
)
)
Run Code Online (Sandbox Code Playgroud)
所有属性都通过魔法访问 __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'");
}
Run Code Online (Sandbox Code Playgroud)
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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
在一个地方,我偶然写到了尚未创建的$this->session->user->id = $user->id地方$this->session->user.所以null->id实际上是(new stdClass())->id.好的,谢谢你,PHP.
因为它表示未定义的属性所在stdClass,这意味着所讨论的对象实际上并不是User您认为的类.
这通常意味着对象的创建出了问题.因此,导致此错误的代码中的实际错误在程序中比您给我们的代码行早.
查找对象的创建位置.这就是问题可能出现的地方.
如果没有看到其余的代码,我就无法获得更多的帮助,但希望有所帮助.
[编辑]
抛出错误的对象是$this->session->user(这是您尝试访问该->roles属性的对象).
尽管你想说它绝对是一个User对象,但事实是PHP说不然.var_dump($this->session->user)在错误发生之前做一个,你应该能够看到我在说什么.
至于为什么不是你所期望的,我仍然无法给出任何更好的答案.使用xDebug之类的调试器一次一行地跟踪程序可能会有所帮助.
| 归档时间: |
|
| 查看次数: |
67657 次 |
| 最近记录: |