March 25, 2012

Working with extended classes in PHP

Question by epic_syntax

I have 2 classes looking like this:

class db {

    protected $db;

    function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error);
        $this->db->set_charset('utf8');
    }

}

and

class sample extends db {

    protected $js_base_dir;

    public function __construct($js_base_dir = js_dir) {
        $this->js_base_dir = $js_base_dir . "/";
    }
 ....

I want to use $this->db inside second class, but __construct in sample class overrides first classes construct function. How to get $this-> db inside second class? Am I doung something wrong? if yes what’s proper way?

Answer by Starx

You can call parent class method, using parrent::methodName(). Similarly, you can use this to invoke parent’s constructor method as well as

parent::__construct();

Usage:

public function __construct($js_base_dir = js_dir) {
    parent::_construct();
    $this->js_base_dir = $js_base_dir . "/";
}

Apart from the manual read this article for extended explanation.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!