简体   繁体   中英

Child class function calling parent class contruct twice

I have 2 classes named C and P as follow:

<?php 
class P{
    var $a;
    function __construct(){
        echo "hello";
    }
    function func($a){
        echo "parent";
    }   
}
class C extends P{
    function func($a){
        echo "child";
    }
    function callpar(){
        parent::__construct();
    }
}
$obj=new C;
$obj->callpar();
?>

Why my output showing hello two times? I just want to call parent class construct for one time.

Parent constructor should only be called from the child constructor.

If a child class doesn't have it's own constructor, the parent constructor is called automatically (like in your case).

If a child class does have it's own constructor and does not call the parent constructor inside, a warning is shown Parent Constructor is Not Called . You must explicitly call the parent constructor in the child constructor. Some languages do this implicitly (like C#), but PHP doesn't. Java even forces you to call the parent constructor in the first line of the child constructor.

Take a look at these 2 examples below:

class P {
    function __construct() {
        echo 'P';
    }
}
class C extends P {
// this child class doesn't have it's own constructor, so the parent constructor is called automatically
}
class D extends P {
    // this class has it's own constructor, so you must explicitly call the parent constructor inside of it
    function __construct() {
        parent::__construct();
        echo 'D';
    }
}

$c = new C; // outputs P
$d = new D; // outputs PD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM