Part of the problem with the base class when PHP creates a derived class object

Before I thought that when calling the constructor of a derived class, the members of the base class cannot be used before the constructor of the base class is called, because the base class object has not yet been constructed and the members do not exist, but I found in the following test, Before calling the constructor of the base class, the members in the base class already exist, and the base class constructor only changes the value of the members in the base class:

class base {
    
    
    public $i = 4;
    
    public function func() {
    
    
        print("in base's func" . PHP_EOL);
    }
    
    public function __construct() {
    
    
        print("in base's construct" . PHP_EOL);
        $this->i = 3;
    }
}

class derive extends base {
    
    
    public function __construct() {
    
    
        print("start derive's constructor" . PHP_EOL);
        self::func();
        print("before base's construct: \$i = $this->i" . PHP_EOL);
        parent::__construct();
        print("after base's construct: \$i = $this->i" . PHP_EOL);
    }
}

$deriveObj = new derive();

Run the above code: It
Insert picture description here
can be seen that the member functions and data members of the base class can be called before the constructor of the base class is run.

Guess you like

Origin blog.csdn.net/tus00000/article/details/115123352