Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override parent's parent's constructor in PHP

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?

like image 319
fredley Avatar asked Nov 23 '10 23:11

fredley


People also ask

Can I override constructor in PHP?

In PHP, the only rule to overriding constructors is that there are no rules! Constructors can be overridden with any signature.

How can we call a constructor from parent class in PHP?

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();

What does parent __construct () do?

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".

How do you call a constructor from a parent class?

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.


1 Answers

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');
    }
}
like image 193
rojoca Avatar answered Sep 26 '22 08:09

rojoca