【发布时间】:2013-12-30 12:01:24
【问题描述】:
下面是我的基类,即数据库方法。
// Constructor
public function __construct($argHost, $argUsername, $argPassword, $argDatabase)
{
$this->_host = $argHost;
$this->_username = $argUsername;
$this->_password = $argPassword;
$this->_database = $argDatabase;
}
// Connect to the database
public function Connect()
{
if (!$this->Is_Connected()) {
$this->_connection = mysqli_connect($this->_host,$this->_username,$this->_password,$this->_database);
} else {
return $this->_connection;
}
}
// Run query
public function Run($query)
{
if ($this->result = mysqli_query($this->_connection,$query)) {
return $this->result;
} else {
die("Couldn't perform the request");
}
}
我的子类是下面的分类方法
class Categories extends Database
{
public $category_id = '';
public $category_name = '';
public $category_image = '';
// View Category
public function ViewCategories()
{
return $this->Run("SELECT * FROM categories");
}
}
现在的问题是,当我通过创建基类的对象来运行 Run() 方法时,它工作正常。但是当我创建对象对象时,子类即类别并执行方法 viewCategories();我收到以下错误
警告:Database::__construct() 缺少参数 1,调用 E:\xampplite\htdocs\ecommerce\index.php 在第 16 行并在 E:\xampplite\htdocs\ecommerce\classes\class.database.php 第 17 行
警告:缺少调用 Database::__construct() 的参数 2 E:\xampplite\htdocs\ecommerce\index.php 在第 16 行并在 E:\xampplite\htdocs\ecommerce\classes\class.database.php 第 17 行
警告:Database::__construct() 缺少参数 3,调用 E:\xampplite\htdocs\ecommerce\index.php 在第 16 行并在 E:\xampplite\htdocs\ecommerce\classes\class.database.php 第 17 行
警告:Database::__construct() 缺少参数 4,调用 E:\xampplite\htdocs\ecommerce\index.php 在第 16 行并在 E:\xampplite\htdocs\ecommerce\classes\class.database.php 第 17 行
警告:mysqli_query() 期望参数 1 为 mysqli,给定 null 在 E:\xampplite\htdocs\ecommerce\classes\class.database.php 第 35 行 无法执行请求
更新:这就是我调用方法的方式
<?php
function __autoload($class_name) {
include 'classes/class.'.$class_name . '.php';
}
$connection = new Database("localhost", "raheel", "raheel786", "ecommerce");
$connection->Connect();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ecommerce</title>
</head>
<body>
<?php
$category = new Categories();
$category_list = $category->ViewCategories();
var_dump($category_list);
?>
</body>
</html>
请帮我解决这个问题。
【问题讨论】:
-
你没有将任何参数传递给构造函数
-
在你的子类中定义一个空的构造函数来覆盖父类中的构造函数;否则继承规则适用,父构造函数将被调用
-
我通过它让我更新代码