我有一个主类和一个扩展类(数据库连接)。
父类名Classica
扩展DatabaseQ
如何调用父类中的扩展类方法?
这不起作用:
$this->connectdb();
或者这个:
$this->DatabaseQ->connectdb();
示例代码:
扩展
class DatabaseQ extends Classica{
public $dbhost;
public $dbname;
public $dbuser;
public $dbpass;
function __construct(){
include('config.php');
$this->dbhost = $dbhost;
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
}
#connect to database
public function connectdb(){
$link = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$link) {
die('Could not connect: ' . mysql_error());
}else {
//echo 'Connected Successfully to Database<br>';
}
@mysql_select_db($this->dbname) or die( "Unable to select database!");
}
#read database
function readdb(){
}
#update database
private function updatedb(){
}
#close database connection
function closedb(){
mysql_close();
}
}
家长
class Classica{
function sample_method(){
//connect db here
//run some sql queries here
}
最佳答案
从您的两个类的内容来看,您绝对没有理由使用 Classica
类,因为当您可以将功能职责分散到多个类时,您没有必要将功能职责分散到多个类中。所有这些都包含在一个类中。
我发现您使用“父”类的唯一原因是连接到数据库并执行一些初始查询。除非您计划稍后实现一些高级设计模式,否则绝对没有理由不能在 DatabaseQ 构造函数中执行此操作。
class DatabaseQ {
public $dbhost;
public $dbname;
public $dbuser;
public $dbpass;
function __construct(){
include('config.php');
$this->dbhost = $dbhost;
$this->dbname = $dbname;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->connectdb(); // This is a good place to initiate your DB connection
$this->doOtherInitStuff(); // Calling the rest of the init stuff.
}
/**
* This is the place where you do all of your init stuff.
* Note the private status! The environment doesn't need to have access to your DB initialization stuff
*/
private function doOtherInitStuff() {
// Do init stuff
}
#connect to database
private function connectdb(){ // Note the private scope too! Only the object itself needs to know how to connect to the db!
$link = mysql_connect($this->dbhost,$this->dbuser,$this->dbpass);
if (!$link) {
die('Could not connect: ' . mysql_error());
}else {
//echo 'Connected Successfully to Database<br>';
}
@mysql_select_db($this->dbname) or die( "Unable to select database!");
}
#read database
function readdb(){
}
#update database
private function updatedb(){
}
#close database connection
function closedb(){
mysql_close();
}
}
另一方面,如果您打算创建一个基类,稍后将用于不同的数据库“驱动程序”(具有重载方法的扩展类),您可以创建一个抽象类,其中仅包含所有数据库“驱动程序”的蓝图您的扩展(驱动程序)类需要实现的方法。
但这有点高级:)
编辑:如果您需要一个专门用于输出 DatabaseQ 检索的内容的类,则创建 DatabaseQ 的扩展类并将所有将吐出数据的内容放入其中。
class DatabaseQOutput extends DatabaseQ {
public function __construct(){
parent::__construct(); // You make sure here that the parents constructor is executed and a DB connection and initialization stuff is taken care off
}
public function output() {
}
}
$db = new DatabaseQOutput();
$db->output();
但说实话,您实际上并不希望任何数据库特定类负责输出数据,因为通常这不是它们的工作。数据库类应该被视为模型,尽管您没有使用 MVC,这意味着它们的作用主要是充当数据库和所有数据获取/发送操作的抽象层。
如果我是你,我会创建一个类,专门负责输出通过数据库类检索的数据。这样,您将创建一个类,该类在某种程度上充当 View ,并将承担输出数据的所有责任。
关于php - 调用扩展类方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919157/