Undefined variable: pdo, call to a member function prepare() on null(未定义变量: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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未定义变量:pdo,在 null 上调用成员函数 prepare()


- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP - if 语句中的倒序 2021-01-01