$ this变量的致命错误

时间:2013-11-29 07:25:26

标签: php variables object this message

我得到一个致命的错误,说我不能在不在对象上下文中时使用$this变量: - 致命错误:在第29行的C:\ xampp \ htdocs \ ooplr \ classes \ DB.php中不在对象上下文中时使用$ this

基本上,我正在尝试设计一个复杂的用户登录系统。以下是DB.php文件的代码:

 <?php

   class DB{
        private static $_instance = null;
        private $_pdo, 
        $_query, 
        $_error = false, 
        $_results, 
        $_count =0;

    private function __construct(){

        try {
            $this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
        } catch(PDOException $e) {
            die($e->getMessage());
        }

    }
    public static function getInstance(){
        if(!isset(self::$_instance)){
            self::$_instance = new DB();

        }
        return self::$_instance;
    }                   
    public static function query($sql, $params=array()){

        $this->_error = false; <--- Error code comes from this line!
        if($this->_query = $this ->_pdo-> prepare($sql)){
            $x=1;
            if(count($params)){
                foreach($params as $param){
                $this -> _query->bindValue($x, $param);
                $x++;
                }
            }
            if($this->_query->execute()){
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count =$this->_query->rowCount();
            } else {

                $this->_error = true;

            }

        }
        return $this;

    }
    private function action($action, $table, $where = array()){
        if(count($where)===3){
            $operators = array('=','>','<','>=','<=');
            $field = $where[0];
            $operator = $where[1];
            $value = $where[2];
        }
        if(in_array($operator, $operators)){
            $sql ="{$action} FROM {$table} WHERE {$field} {$operator} ?";
            if($this->query($sql, array($value))->error()){
                return $this;
            }
        }
        return false;
    }

    public function get($table,$where){
        return $this->action('SELECT*',$table, $where);
    }

    public function delete($table, $where){
        return $this->action('DELETE',$table, $where);
    }

    public function error(){
        return $this->_error;
    }


}

我如何修复该行: $ this-&gt; _error = false; 以及如何将其置于“对象上下文”中?

2 个答案:

答案 0 :(得分:3)

您已将query方法声明为静态。 $this需要一个实例来引用,因此您不能在静态方法中使用它。

您需要正确实例化您的类,并使用 - 静态方法来使用$this

请注意,您的__construct()方法应声明为公开。

答案 1 :(得分:1)

如果你想在静态方法中使用变量,它们也必须声明静态,所以如果你想使用$ _error声明它:

static public $_error

并在静态方法中使用它,如下所示:

self::$_error