Yii::app()->user->id is not returning the empty re

2019-06-05 12:16发布

I've a problem, it might be a small one but I couldn't find the solution for this. Yii:app()->user->getId() or Yii:app()->user->id is not returning value. it just returning empty result. But I've set the id in my UserIdentity class.

in my UserIdentity class I've this,

public function getId()
{
   return $this->id;
}

I'm setting id in the autheticate() function. if i displayed there itself it's displaying the id, but not in getId() function. Please help me in this.

Thanks in advance.

Dhanendran Rajagopal.

标签: php yii
2条回答
神经病院院长
2楼-- · 2019-06-05 13:06

Not sure if you are using the standard UserIdentity class, but in the standard one id is a private attribute and in Yii convention private attributes have _ in front of them, so it would be like this:

public function getId()
{
    return $this->_id;
}

Since it is private variable you can't access it with Yii::app()->user->_id. The getId() function is a magic function, when you run Yii::app()->user->id, it sees there is no id attribute so looks for a function named getId() and runs it if it exists.

If you are using the standard class you need to change this as you stated in your comment below:

$this->_id = $user->user_id //underscore added before id
查看更多
戒情不戒烟
3楼-- · 2019-06-05 13:11

Refactor your getId() function like this!

public function getId(){
    return $this->getState('id');
}

This problem begin when you set the user states in your Identity. You try to set state, and then get an attribute!

查看更多
登录 后发表回答