【问题标题】:DB Conect Class Error数据库连接类错误
【发布时间】:2014-11-01 04:59:11
【问题描述】:
class DB 
{
    private static $_instance;
    private $_pdo,
            $_query,
            $_error = false,
            $_results,
            $_count = 0;

    private function __construct()
    {   
       try{
        $this->_pdo = new PDO($dsn, $user, $password);
       } catch(PDOException $e)
       {
        die($e->getMessage()); 
       }
    }

    private static function getInstance()
    {
        if(!isset(self::$_instance))
        {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }

}

当我尝试使用 $db = DB::getInstance(); 获取实例时我得到:致命错误:从上下文调用私有方法 DB::getInstance() ''

我做错了什么?

【问题讨论】:

  • catch 和 die 没有任何意义。

标签: php class dbconnection


【解决方案1】:

您应该了解visibility 和简单模式singleton。 替换

private static function getInstance()

有

public static function getInstance()

还有。你认为在哪里为 PDO 取参数?

【讨论】:

    【解决方案2】:

    您正在使用 DB 类作为抽象类,您应该创建它的一个对象。你还应该传递 $dsn、$user、$password。

    class DB 
    {
        private static $_instance;
        private $_pdo,
                $_query,
                $_error = false,
                $_results,
            $_count = 0;
    
        public function __construct($dsn, $user, $password)
        {   
           try{
            $this->_pdo = new PDO($dsn, $user, $password);
           } catch(PDOException $e)
           {
            die($e->getMessage()); 
           }
        }
    
        public static function getInstance()
        {
            if(!isset(self::$_instance))
            {
                self::$_instance = new DB();
            }
            return self::$_instance;
        }
     }
    

    用法

     $db = DB('dsn','user','password');
     $db->getInstance()
    

    如果我错了对不起!

    【讨论】:

      【解决方案3】:

      除了@sectus 指出的,构造函数永远不会返回任何东西,所以 self::$_instance = new DB(); 真的没有意义,考虑将该逻辑移至函数本身:

      if(!isset(self::$_instance))
      {
          try{
              self::$_instance = new PDO($dsn, $user, $password);
          } catch(PDOException $e){
              die($e->getMessage()); 
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-21
        • 1970-01-01
        • 2012-10-29
        • 2018-05-23
        • 2012-09-29
        • 2014-10-04
        • 2013-08-28
        相关资源
        最近更新 更多