Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

php - Using $this when not in object context?

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

         }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...