Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make instance of one class to be instance of another class

Tags:

oop

php

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();
like image 447
codez Avatar asked Nov 17 '25 09:11

codez


1 Answers

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();
like image 111
Mironor Avatar answered Nov 19 '25 23:11

Mironor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!