本文介绍了未定义变量:pdo,在 null 上调用成员函数 prepare()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在关注一个视频并仔细检查所有代码,一切似乎都一样,但我遇到了这些错误.
I was following a video and double checking all code and everything seems to be the same yet I get these errors.
错误:
注意:未定义变量:第 14 行 QueryBuilder.php 中的 pdo
致命错误:在 QueryBuilder.php 第 14 行调用成员函数 prepare() 为 null
QueryBuilder.php:
class QueryBuilder
{
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function selectAll($table)
{
$query = $pdo->prepare("SELECT * FROM `$table`"); // --> LINE 14 <--
$query->execute();
return $query->fetchAll();
}
}
Connection.php:
class Connection
{
public static function make()
{
$servername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "test";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$dbName", $dbUsername, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
catch(PDOException $e){
die($e->getMessage());
}
}
}
init.php:
require "database/Connection.php";
require "database/QueryBuilder.php";
require "app/Product.php";
$query = new QueryBuilder(Connection::make());
推荐答案
如评论中所述,在 OOP 中,您需要使用 $this->pdo
为其传递对象的属性,而不是变量 $query = $pdo->
,因为你已经在:
As stated in comments, in OOP, you need to use $this->pdo
passing the object's property for it, instead of the variable $query = $pdo->
since you've construct'ed it in:
public function __construct($pdo)
{
$this->pdo = $pdo;
^^^^^^^^^^
}
即:
$query = $this->pdo->prepare
这篇关于未定义变量:pdo,在 null 上调用成员函数 prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!