【问题标题】:Using $this when not in object context [closed]不在对象上下文中使用 $this [关闭]
【发布时间】:2015-06-25 21:36:46
【问题描述】:

此代码在我的user.php 文件中

include('password.php');
class User extends Password{

        private $_db;

        function __construct($db){
            parent::__construct();

            $this->_db = $db;
        }

        private function get_user_hash($email){ 

            try {
                $stmt = $this->_db->prepare('SELECT password FROM users WHERE email = :email AND active="Yes" ');
                $stmt->execute(array('email' => $email));

                $row = $stmt->fetch();
                return $row['password'];

            } catch(PDOException $e) {
                echo '<p class="bg-danger">'.$e->getMessage().'</p>';
            }
        }

        public function login($email,$password){

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

            if($this->password_verify($password,$hashed) == 1){

                $_SESSION['loggedin'] = true;
                return true;
            }   
        }

        public function logout(){
            session_destroy();
        }

        public function is_logged_in(){
            if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
                return true;
            }       
        }
    }

这段代码是我login.php 文件的一部分

function login($email,$password){

$hashed = $this->get_user_hash($email);  <--the error is in this line

if($this->password_verify($password,$hashed) == 1){

    $_SESSION['loggedin'] = true;
    return true;
}     

老实说,我不知道该怎么做,我还在学习这些东西,而且我对类和对象并不是很擅长,这就是为什么我要求大家帮助我解决这个问题。

【问题讨论】:

  • 您遇到了什么问题?
  • @MTahir 我已经解决了我之前提出的问题。但我现在的问题是“在 null 上调用成员函数 prepare()”。你能帮我解决这个问题吗?

标签: php function class object


【解决方案1】:

替换这一行

$hashed = $this->get_user_hash($email);  <--the error is in this line

$user = new User($db);
$hashed = $user->get_user_hash($email);

你不能在课堂外使用它。您可以在下面的 SO 帖子中了解有关 $this 的更多信息。 What does the variable $this mean in PHP?

【讨论】:

  • 错误变为“从上下文调用私有方法User::get_user_hash()”你知道怎么解决吗?谢谢:)
  • 如果要访问外部函数,您需要将方法声明为公共。从函数定义中删除 private 关键字。
  • 现在它更改为“在 null 上调用成员函数 prepare()”,我不知道这是什么意思。抱歉,我真的很陌生。
  • 所以不能代替一个好的教程。您的问题是如此基本,以至于您需要有关 PHP 课程的教程和基本培训是显而易见的。通过在这里询问来一一解决错误对您没有帮助。
  • @EdRyanEstrella 您的 $db 对象未正确传递。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多