我在使用mySQL和SQLite DB的项目中工作。我的目标是使代码能够使用这两种数据库类型。我使用mysqli
类为mySQL开发了代码,现在我想修改它以使它也能与SQLite3
个对象一起使用。
SQLite3
类实现与mysqli
相同的方法(至少是我使用的方法),但有时使用不同的名称。例如,mysqli::fetch_array()
变为SQLite3::fechArray()
。所以我扩展SQLite3和SQLite3Result
类来实现我需要的方法。例如:
class SQLite3ResultEx extends SQLite3Result {
public function fetch_array() {
return parent::fetchArray();
}
}
问题在于我不知道如何扩展SQLite3
课程的响应以获得我自己的SQLite3Response
扩展课程。我的意思是:
class SQLite3Ex extends SQLite3 {
public function __construct($filename, $flags = null, $encryption_key = null) {
return parent::__construct($filename, $flags, $encryption_key);
}
public function query($query) {
$res = parent::query($query);
return $res;
}
}
现在$res
是一个SQLite3Result
对象,但我需要它成为SQLite3ResultEx
对象(我自己的扩展类)。
答案 0 :(得分:1)
一种方法是进一步抽象它,而不是扩展SQLite3Result
,你可以创建一个接受SQLite3Result
对象的新类,提供自己的方法然后代理结果
class myResults
{
/**
* @var SQLite3Result
*/
protected $result;
/**
* Constructor
* @param SQLite3Result $result
*/
public function __construct(SQLite3Result $result)
{
$this->result = $result;
}
/**
* Fetch array of results
* @return array
*/
public function fetch_array()
{
return $this->result->fetchArray();
}
// Any other methods you need
}
然后您的SQLite3Ex::query
方法变为:
/**
* Preform query
* @param string $query
* @return myResults
*/
public function query($query)
{
$res = parent::query($query);
return new myResults($res);
}
答案 1 :(得分:-1)
您可以尝试创建$ res作为子类的特定参数,并直接用
引用它$this->res = ...
以便你的子类看起来像:
class SQLite3Ex extends SQLite3 {
private $res;
public function __construct($filename, $flags = null, $encryption_key = null) {
return parent::__construct($filename, $flags, $encryption_key);
}
public function query($query) {
$this->res = parent::query($query);
return $res;
}
}