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.