Using $ this if not in the context of an object?

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

         }

      

-2


source to share


1 answer


You are using $this

in a static function. $this

refers to an instance you don't have that is calling a static function, hence an error. I don't understand why you need non-static properties in a singleton class, but if you insist that this is what you can do



catch(PDOException $e) { 
    self::$instance->error = $e->getMessage();     
}

      

0


source







All Articles