在一个类中拆分一个函数

时间:2014-07-11 04:57:23

标签: php

这是一个类中的函数,它可以正常工作

public function login($username,$password){

        $hashed = $this->get_user_hash($username);

        try {
            $stmt = $this->_db->prepare('SELECT username FROM members WHERE password = :password AND active="Yes" ');
            $stmt->execute(array('password' => $hashed));
            $row = $stmt->fetch();
            $_SESSION["uname"] = $row['username'];
        }
        catch(PDOException $e) {
            echo '<p class="bg-danger">'.$e->getMessage().'</p>';
        }

        if($this->password_verify($password,$hashed) == 1){
            $_SESSION['loggedin'] = true;
            return true;
        }   
    }

现在,我想将上面的代码分成两个函数

public function login($username,$password){

    $hashed = $this->get_user_hash($username);

    if($this->password_verify($password,$hashed) == 1){
        $_SESSION['loggedin'] = true;  // this works
        return true;
    }   
}

以上代码也有效,但在下面的部分我无法获得$_SESSION["uname"]

的值
public function get_uname(){

        $hashed = $this->get_user_hash($username);

        try {
            $stmt = $this->_db->prepare('SELECT username FROM members WHERE password = :password AND active="Yes" ');
            $stmt->execute(array('password' => $hashed));
            $row = $stmt->fetch();
            $_SESSION["uname"] = $row['username'];  // this doesn't work
        }
        catch(PDOException $e) {
            echo '<p class="bg-danger">'.$e->getMessage().'</p>';
        }

    }

1 个答案:

答案 0 :(得分:2)

当你退后一步看它时,它实际上很简单。

你的第一个功能是这样的:

public function login($username,$password){

请注意,您传递了$username,其被接听:

 $hashed = $this->get_user_hash($username);

在新的拆分功能中,您不会传递$username

public function get_uname(){

    $hashed = $this->get_user_hash($username); //where is username coming from?

因此,当输入为空(可能为假)时,大概$this->get_user_hash()将返回您编程的任何内容,因此您的查询无效,因为$hashed没有任何意义。有意义吗?