我正在关注视频并仔细检查所有代码,所有内容似乎都相同,但我收到了这些错误。
错误:
注意:未定义的变量:第14行的QueryBuilder.php中的pdo
致命错误:在第14行的QueryBuilder.php中调用null上的成员函数prepare()
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());
答案 0 :(得分:2)
正如评论中所述,在OOP中,您需要使用$this->pdo
传递对象的属性,而不是变量$query = $pdo->
,因为您已经构建了&#39;编辑:
public function __construct($pdo)
{
$this->pdo = $pdo;
^^^^^^^^^^
}
即:
$query = $this->pdo->prepare