【问题标题】:Using $this when not in object context?不在对象上下文中使用 $this?
【发布时间】:2023-03-22 06:14:01
【问题描述】:

错误信息:

致命错误:使用 $this 时 不在第 51 行的 class.db.php 中的对象上下文中

错误行:

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

代码:

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

         }

【问题讨论】:

  • 你的prepare方法被声明为static,但是如果你静态调用一个方法,你就不能使用$this,因为没有对象。

标签: php pdo singleton


【解决方案1】:

您在静态函数中使用$this$this 指的是您没有的实例,它调用静态函数,因此出现错误。我不明白为什么你需要在单例类中使用非静态属性,但如果你坚持拥有它们,这就是你可以做的

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

【讨论】:

  • 非常感谢您的理解。我决定使用非静态函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2013-12-14
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多