I have one PHP class thus:
class DB extends mysqli{
public function __construct(
{
parent::__construct('localhost','user','password','db');
}
}
My problem is that I want to override this class with a new one that performs more privileged database operations with a different db user.
class adminDB extends DB{
public function __construct(
{
??
}
}
}
What should I do here?
In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();
We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".
Define a constructor in the child class To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.
You should pass the credentials to the constructor anyway:
class DB extends mysqli {
public function __construct($host, $user, $password, $db)
{
parent::__construct($host, $user, $password, $db);
}
}
Then you don't need inheritance you can just use:
$adminDb = new DB($adminHost, $adminUser, $adminPassword, $db);
$nonAdminDb = new DB($host, $user, $password, $db);
But if you really want inheritance you could still do this:
class AdminDB extends DB {
public function __construct() {
parent::__construct('adminhost','adminuser','adminpassword','db');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With