douwei2825 2016-07-30 20:48
浏览 44
已采纳

调用未定义的方法connect :: prepare()

Every time I try to execute the query it shows:

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

// this in another page 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);
  • 写回答

3条回答 默认 最新

  • duancuan7057 2016-07-30 21:00
    关注

    In connect, you have PDO in a $pdo property. In users, you have connect in a $pdo property. To access PDO from users, you would then need to use $this->pdo->pdo. This is where naming is going to get confusing for you.

    If you're only using this class to maintain one instance of PDO (singleton pattern), then there is no reason to use magic functions here, just return the PDO object in getInstance() instead of an instance of connect:

            /**
             * @return PDO
            */
            public static function getInstance() {
                if(!isset(self::$instance)) {
                    self::$instance = new connect();
                }
                return self::$instance->pdo;
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?