2016-07-30 22 views
-1

每次我試圖執行查詢它表明:調用未定義的方法連接::準備()

fatal error: Call to undefined method connect::prepare()

 class connect { 

      private static $instance = null; 
      private $pdo; 

      private function __construct() { 
       try{ 
        $this->pdo = new PDO('mysql:localhost=127.0.0.1;dbname=comment', 'root', ''); 
       } catch(PDOException $e) { 
        die($e->getMessage()); 
       } 
      } 

      public static function getInstance() { 
       if(!isset(self::$instance)) { 
        self::$instance = new connect(); 
       } 
       return self::$instance; 
      } 
     } 

//這個在另一頁require_once 'connect.php';

class users { 
    public $pdo; 

    public function __construct() { 
     $this->pdo = connect::getInstance(); 
    }  



    public function insertComment($user_id, $comment_text, $time) { 

     $sql = "INSERT INTO comments VALUES ('','$user_id', '$comment_text', '$time')"; 
     $this->query = $this->pdo->prepare($sql); 
     $this->query->execute(); 

    } 

} 

$user = new users; 
$user_id = 10; 
$comment_text = 'hello everyone'; 
$time = date("y/m/d - h:i:s"); 
$user->insertComment($user_id, $comment_text, $time); 
+0

在connect中,您在$ pdo屬性中擁有PDO。在用戶中,你有一個$ pdo屬性連接。要從用戶訪問PDO,您需要使用'$ this-> pdo-> pdo'。這是命名會讓你感到困惑的地方。 – Devon

+0

它不工作,你能解釋更多,以得到整個想法 –

+1

我的技巧是擺脫你的班'連接'。 PDO已經是一個配備齊全的db-class。無需將其包裝在自定義的一個! – Jeff

回答

0

在連接,你有PDO在$pdo屬性。在用戶中,您已連接$pdo屬性。要從用戶訪問PDO,您需要使用$this->pdo->pdo。這是命名會讓你感到困惑的地方。

如果您只使用這個類來維護一個PDO實例(單例模式),那麼沒有理由在這裏使用魔術函數,只需返回getInstance()中的PDO對象而不是connect實例:

 /** 
     * @return PDO 
     */ 
     public static function getInstance() { 
      if(!isset(self::$instance)) { 
       self::$instance = new connect(); 
      } 
      return self::$instance->pdo; 
     } 
0

你想$this->pdo->pdo->prepare($sql);,這是目前無法訪問,因爲$pdo目前在connect類私有。

$this->pdo指的是你的第一個(這似乎是數據庫類connect),在那裏你再次分配$this->pdo是你要達到(添加到您的connect類)實際PDO數據庫類。

你可以使用魔術方法__call轉發這些請求到父PDO類:

public function __call($method, $args) 
{ 
    if (method_exists($this->pdo, $method)) 
    { 
     return call_user_func_array(array($this-pdo, $method), $args); 
    } 
} 
0

您必須瞭解面向對象編程中的封裝。當你將變量聲明爲私有變量時,它不能在類之外解析。讓我說你正在申報

private $pdo 

你不能在用戶類中看到該變量,它在連接類中唯一可見。 在你的用戶類中,你已經有了$ pdo來連接實例(singleton實例),但是當你在用戶類中使用$ pdo時,你嘗試訪問不是的本地pdo。 所以請使用getter/setter作爲私有變量。在Connect類:

function getPDO(){ 

    return $this->pdo; 
    } 
    // You dont need setter because you may will not use another driver in lifecyle 

所以,當你想給你打電話使用此快捷方式的數據庫驅動程序毫無疑問

connect::getInstance()->getPDO(); 

請不要猶豫,馬上問評論什麼。希望幫助!

相關問題