为什么我在加载 pdo 时会'call to a member function prepare() on null'?



将 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'; 

连接.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()); 
}
}
}

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

$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()); 
}
}

相关内容

最新更新