Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 致命错误:在第33行的null上调用成员函数prepare()_Php_Debugging_Pdo - Fatal编程技术网

Php 致命错误:在第33行的null上调用成员函数prepare()

Php 致命错误:在第33行的null上调用成员函数prepare(),php,debugging,pdo,Php,Debugging,Pdo,下面是我正在工作的代码示例 我在第33行遇到一个致命的错误,如果你能非常感谢的话,请帮助我 private $dbh; private $error; private $stmt; public function __construct() { // set DSN $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

下面是我正在工作的代码示例 我在第33行遇到一个致命的错误,如果你能非常感谢的话,请帮助我
     private $dbh;
     private $error;
     private $stmt;

    public function __construct() {
         //  set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
         // set options
         $options = array (
              PDO::ATTR_PERSISTENT => true,
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
         );
         //  create a new PDO instance
        try {
        $this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
        }
        //  catch any errors

         catch(PDOException $e){
            $this->error = $e->getMessage();
         }
    }

    public function query($query) {
       $this-> stmt = $this-> dbh->prepare($query); 
    }

看起来,即使捕捉到错误,您仍在继续运行查询函数,因此,如果构造失败,$dbh将永远不会被初始化。

您使用异常的方式是错误的

让你的代码像这样

public function __construct() {
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    $options = array (
          PDO::ATTR_PERSISTENT => true,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );
    $this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
}

public static function __call($method, $args)
{
    return call_user_func_array(array($this->dbh, $method), $args);
}

public static function run($sql, $args = [])
{
    $stmt = $this->dbh->prepare($sql);
    $stmt->execute($args);
    return $stmt;
}
这就是您可能需要用于包装器的所有代码。所有其他代码都是错误和多余的