Yii2:如何在对象上调用validatePassword()?

时间:2015-08-20 05:59:08

标签: php yii2

我遇到与this question on stackoverflow类似的问题。我收到的错误是

Call to a member function validatePassword() on a non-object

在我的Users模型上,我使用findOne()方法返回User对象。当我尝试在我的LoginForm方法上使用此方法验证用户时,我收到了我所说的错误。

public function getUserStatus()
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if($user || $user->validatePassword($this->password)) {
            if($user->user_status == 0) {
                return 1;
            } else {
                return 8;
            }
        } else {
            return -1;
        }
    }
}

我的getUser与Yii2高级模板上的相同。

public function getUser()
{
    if ($this->_user === false) {
        $this->_user = Users::findByEmail($this->email, self::USER);
    }

    return $this->_user;
}

我面临的问题是,在调用它时没有错误:

if(!$user || !$user->validatePassword($this->password))

然而这有错误:

if($user || $user->validatePassword($this->password))

我认为这与PHP对象本身而不是框架有什么关系?

1 个答案:

答案 0 :(得分:4)

首先检查$user是否不是NULL。在您的 if语句中,您将面临PHP优化(假设$userNULL

if(!$user || !$user->validatePassword($this->password))
=
if (true || unknown) // first argument is satisfied and no further actions are taken (second condition is ignored)
if($user || $user->validatePassword($this->password))
=
if (false || unknown) // first argument is not satisfied, so PHP continues to check second parameter, thus leading to `NULL->validatePassword()`

if (false && someCondition)相同 - 优化有效。

解决这个问题:

if ($user && $user->validatePassword()) { // If first argument is `false`, don't evaluate second argument. If it's `true` - validate password

if ($user) {
    if ($user->validatePassword()) {
       // valid
    } else {
       // not valid
    }
} else {
    //error
}

您的示例

public function getUserStatus()
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();

        if($user && $user->validatePassword($this->password)) {
            return $user->user_status == 0;
        }
    }

    return -1;
}