I have custom db class which extends MySQLi class MySQLi->query() method returns obejct with MySQLi_Result class, but I want to extend funcionality of this class and somehow make result object to be MyResult class. Something like this:开发者_高级运维
class MyResult extends MySQLi_Result{
function abc(){
//...
}
}
class MyDB extends MySQLi{
function q($query){
return /*Here some magic*/ $this->query();
}
}
$db=new MyDB();
$res=$db->q('SEL...');
$res->abc();
How to do this?
EDIT: Some say that this is duplicate, but problem here is deeper! I need that $result object would act like Mysqli_result class obect, so the old code would work. So I need that, I can call original Mysqli_result methods like:
$res->fetch_assoc();
//but not
$res->result->fetch_assoc();
You can apply the Decorator pattern So your code will be:
class MyResult {
private $result;
function __construct(MySQLi_Result $result)
{
$this->result = result;
}
//Here some methods that use $this->result as you wish
}
class MyDB extends MySQLi{
function q($query){
return new MyResult($this->query($query));
}
}
$db=new MyDB();
$res=$db->q('SEL...');
$res->myMethod();
class MyDB extends MySQLi{
function q($query){
return new MyResult($this->query());
}
}
The MyResult would need a constructor that stores the output of query() and wraps it as you want.
Probably something like this.
class MyDb extends MySQLi {
function query($query) {
$result = parent::query($sQuery);
return new MyDbResult($result);
}
}
I'm not sure if I've understood your question correctly, but it could look something like this.
class MyResult extends MySQLi_Result{
function __Contstruct($ob)
{
return $this->abc($ob);
}
function abc($object){
//your magic
}
}
class MyDB extends MySQLi{
function q($query){
$ob = $this->query($query);
return new MyResult($ob);
}
}
精彩评论