How will a child class constructor interact with a

2019-05-28 19:53发布

问题:

Right now, I am developing two classes for interaction with a MySQL database - one extends the other. Here they are:

class DB_MySQL {

    protected $dbuser;
    protected $dbpass;
    protected $dbhost;
    protected $dbname;
    protected $dbh; // Database connection handle

    public function __construct($dbuser, $dbpass, $dbhost, $dbname)
    {
        $this->dbuser = $dbuser;
        $this->dbpass = $$dbpass;
        $this->dbhost = $dbhost;
        $this->dbname = $dbname;
    }

    //Used to create connections - almost always called by execute()
    protected function connect()
    {
        try
        {
            $this->dbh = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
        }
        catch(PDOException $e)
        {
            print "Error!: ".$e->getMessage()."<br/>";
            die();
        }
    }

And the child class:

class CheckOut extends DB_MySQL{

     function __construct() 
    {
        parent::__construct();
    }
}

I just started writing them, so there is no "meat" to them yet. If anyone sees any major issues or any suggestions, don't hesitate to point it out.

My question, though, is how the child constructor will interact with the parent's. My plan is to simply create a CheckOut object without initiating the parent's. As it can be seen, my parent constructor takes four values. So, do I have to redefine those values in the child constructor? To be clear, I mean:

class CheckOut extends DB_MySQL{

     function __construct($dbuser, $dbpass, $dbhost, $dbname) 
    {
        parent::__construct($dbuser, $dbpass, $dbhost, $dbname);
    }
}

and of course define those variables. Or can I add those values when I create the object and it will implicitly be passed?

Any help is appreciated.

回答1:

If the constructor of the child class doesn't do any other things, then you could omit the constructor.

Just the below is ok:

class CheckOut extends DB_MySQL{
}

But if the child class's constructor need do some other work, yes, you need to do:

class CheckOut extends DB_MySQL{

    public function __construct($dbuser, $dbpass, $dbhost, $dbname) 
    {
        parent::__construct($dbuser, $dbpass, $dbhost, $dbname);
        do_some_other_work();
    }
}

When you use, you both need to call:

$checkout = new CheckOut($dbuser, $dbpass, $dbhost, $dbname);


回答2:

The code you presented in your question is the correct way to do it in this case (assuming that you want to do something else in the constructor):

class CheckOut extends DB_MySQL{
    function __construct($dbuser, $dbpass, $dbhost, $dbname) 
    {
        parent::__construct($dbuser, $dbpass, $dbhost, $dbname);
    }
}

Otherwise (If you don't want to do anything else in the constructor) you don't need to override the constructor.

class CheckOut extends DB_MySQL{

    // no constructor, Parent's constructor is called by default

}