Using $this when not in object context?

2019-09-23 00:21发布

Error message:

Fatal error: Using $this when not in object context in class.db.php on line - 51

Error line:

            return $this->PDOInstance->prepare($sql, $driver_options);

Code:

class DB {   
        public $error = true; 

        private $PDOInstance = null;

        private static $instance = null;

        private function __construct()
          {
            try {

                $this->PDOInstance = new PDO('mysql:host='.HOST.';dbname='.DBNAME.';',
                                                    USER,
                                                    PASSWORD,
                                                    array(
                                                            PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                                                            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
                                                            ));

                $this->PDOInstance->query("SET NAMES 'cp1251'");
            } 
            catch(PDOException $e) { 
                echo "error";
                exit();
            }
          }


        public static function getInstance()
        {  
            if(is_null(self::$instance))
            {
              self::$instance = new DB();
            }
            return self::$instance;
        }


        private function __clone() {
        }

        private function __wakeup() {
        }         

        public static function prepare($sql, $driver_options=array())
        {
            try {
                return $this->PDOInstance->prepare($sql, $driver_options);  /// ERROR in this line
            } 
            catch(PDOException $e) { 
                $this->error($e->getMessage());
            }
        }

         }

1条回答
趁早两清
2楼-- · 2019-09-23 01:00

You're using $this in a static function. $this refers to an instance, which you don't have, calling a static function, hence the error. I don't see why you need non-static properties in a singleton class but in case you insist on having them this is what you can do

catch(PDOException $e) { 
    self::$instance->error = $e->getMessage();     
}
查看更多
登录 后发表回答