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条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)