php - 简单的 PHP OOP 查询 null
问题描述
我正在尝试编写一个简单的程序,该程序使用面向对象的编程向数据库查询 sql。我不断收到错误:
致命错误:未捕获的错误:在 C:\xampp\htdocs\learning\core\classes\core.php:11 中调用成员函数 query() 堆栈跟踪:#0 C:\xampp\htdocs\learning\core \classes\core.php(23): core->query('SELECT * FROM c...') #1 C:\xampp\htdocs\learning\core\classes\core.php(27): test-> test() #2 C:\xampp\htdocs\learning\core\init.php(6): require('C:\xampp\htdocs...') #3 {main} 在 C:\xampp\htdocs 中抛出\learning\core\classes\core.php 在第 11 行
<?php
class core{
protected $db, $results;
private $rows;
public function __construct(){
$this->db = new mysqli('localhost', 'root','','test');
}
public function query($sql){
$this->result = $this->db->query($sql);
}
public function rows(){
for($x = 1; $x <= $this->db->affected_rows; $x++){
$this->rows[] = $this->result->fetch_assoc();
}
return $this->rows;
}
}
class test extends core{
public function test(){
$this->query("SELECT * FROM currentseason");
}
}
$test = new test();
$test->test();
?>
解决方案
您尚未从测试类调用父构造函数。
PHP 文档说:
注意:如果子类定义了构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数中调用 parent::__construct()。如果子类没有定义构造函数 > 那么它可以像普通类方法一样从父类继承(如果它没有被声明为私有)。
我将您的测试类修改如下:(对我的测试数据库中的表进行修改后的查询)
class test extends core {
public function __construct(){
parent::__construct();
}
public function test() {
$this->query("SELECT * FROM bug_table");
foreach ($this->rows() as $row) {
echo $row['category_id'], '<br>';
}
}
}
输出:
Server
Database
Server
Server
Server
...在此处找到的相同 PHP 信息中,我将test()
类构造函数更改__construct
为您在类中的构造core
函数,但保留了test()
运行查询的命名函数。与类同名的构造函数很快就被弃用了。根据您的 PHP 版本,php -l file.php
在文件的命令行上运行以检查任何潜在问题。
推荐阅读
- javascript - 如何在图像顶部按比例放置不同的画布?
- c# - 如何在 TFS 中更新测试套件中特定测试用例的测试结果。不应将所有测试用例标记为 C# 套件中的进行中
- java - 我有一个以文件名作为输入的方法,应该返回一个数组作为输出。该文件包含学生记录以及学科名称和标记
- c# - 如何在 Asp.net c# mvc 中单击类似文件类型 =“文件”的按钮从文件夹和数据库中预览图像
- python - 通过不同的execute_script调用创建和访问js变量
- sql - 如何实现将示例数据库分解为两个不同数据库的脚本?
- android - 如何实现这种简单优雅的微调器布局?
- jenkins - run any command from configuration file
- r - 如何从 R 包重写 C++ 函数
- java - 在 Vaadin Grid 中显示来自 SQL 的数据