Using $this when not in object context?

淺唱寂寞╮ 提交于 2019-12-13 09:39:22

问题


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:


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();     
}


来源:https://stackoverflow.com/questions/20026204/using-this-when-not-in-object-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!