devmonster
devmonster

Reputation: 1739

object oriented programming inheritance

I have created this parent class

class DBMysqli {
    private $mysqli;

    function __construct($Mysqli) {
        $this->mysqli = $Mysqli;
    }

     public function GET($queryArr){

        $query = "SELECT ";

       ...

        $result = $this->mysqli->query($query); //Here I get a run time error!!
        echo $this->mysqli->error;

        return $result;
   }
}

and a child class

class FolderComment extends DBMysqli{

    protected $data;

    public function __construct() {
        $this->mysqli = DB::Simulator(); //works, initiliaze $mysqli
        $table = array(
            'tables' => 'folder_comments',
            'conditions' => '1'
        );

        $this->data = $this->GET($table);
    }
}

I get run time error, stating that the $this->mysqli is null. but I have set it in the child class. I guess this is an OOP understating question.

Upvotes: 0

Views: 90

Answers (4)

GBD
GBD

Reputation: 15981

You need to pass on mysqli object to your parent class

   public function __construct() {
        parent::__construct(DB::Simulator());
        $table = array(
            'tables' => 'folder_comments',
            'conditions' => '1'
        );

        $this->data = $this->GET($table);
    }

Upvotes: 1

lix
lix

Reputation: 517

Change

private $mysqli;

To

protected $mysqli;

In the prent class

Upvotes: 1

Rudu
Rudu

Reputation: 15892

In DBMysqli you need $mysqli to be protected, not private

class DBMysqli {
    protected $mysqli;
    //...

Private says that any access - either external or inherited is prevented, while protected says external access is prevented but inherited objects can access the property.

Upvotes: 0

thatidiotguy
thatidiotguy

Reputation: 9011

I believe that since you have made mysqli a private variable, it is not getting set in the child's constructor as you presume. It should be protected if you want children to be able to access it.

So instead what is happening is that you are creating a new variable in your child class called mysqli, since it never inherited the private field from the parent in the first place.

Your other option would be to call the parent's constructor implicitly and send it the mysqli variable.

Upvotes: 1

Related Questions