0

将 pdo 实例传递给类方法时,我收到此错误(“未捕获的错误:在 null 上调用成员函数 prepare()”)。该错误由 selectAll 方法引发。堆栈跟踪是#0。我无法弄清楚为什么会出现此错误。

class QueryBuilder {


protected $pdo; 

protected $newTask;

public function __construct($pdo) {

  $this->pdo = $pdo; 
}

//Selects from table and returns to view

public function selectAll($table, $intoClass) {

  $stmt = $this->pdo->prepare("select * from {$table} limit 1, 9"); 
  $stmt->execute(); 
  return $stmt->fetchAll(PDO::FETCH_CLASS, $intoClass); 

}

//Adds a new task to the table

public function addToTable($table, $newTask) {

    $done = 0; 

          try {
    $stmt = $this->pdo->prepare("insert into {$table} (description, completed) values (:todo, :done)");
    $stmt->bindParam(':todo', $newTask);
    $stmt->bindParam(':done', $done); 
    $stmt->execute(); 
    } catch(PDOException $e) {
       die($e->getMessage()); 
    }

}

}

这是 index.php 文件,我保存了 pdo 变量。

error_reporting(E_ALL);
ini_set('display_errors', '1');

require "Task.php"; 
require "config.php"; 
require "connection.php"; 
require "QueryBuilder.php"; 

$pdo = Connection::make(); 

$query = new QueryBuilder($pdo); 

$tasks = $query->selectAll('todos', 'Task'); 

$newTask = $_POST['todo']; 

require 'user.view.php'; 

Connection.php 是我初始化 pdo 的地方。

 class Connection { 

  public static function make() {

     try {
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' 
', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
 } catch (PDOException $e) {
     die ($e->getMessage()); 
 }

    }

 }
4

1 回答 1

2

您正在创建的连接是您正在调用的静态函数的返回值:

$pdo = Connection::make();

但是该函数不返回任何内容,从而使该连接对象成为null

public static function make() {
    try {
        $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}

从函数返回连接对象:

public static function make() {
    try {
        return new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e) {
        die ($e->getMessage()); 
    }
}
于 2020-06-05T11:27:42.230 回答