Alex Rivera | Logout

Override parent's parent's constructor in PHP

Asked 2010-11-23T23:05:16.750
10

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?

Edit
Report

1 Answer

12

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');
    }
}
answered 2010-11-23T23:16:03.503

Your Answer