Home >Backend Development >PHP Tutorial >php object-oriented (OOP)—inheritance and compatibility of construction methods in different php versions
PHP4.x version:
The constructor name of PHP 4.x is the same as the class name.
The constructor name of the subclass is the same as the subclass name (nonsense).
The constructor of the parent class will not be executed automatically in the subclass.
To execute the constructor of the parent class in the subclass, you must execute a statement similar to the following:
$this->[Constructor name of the parent class ()]
class base1 {
function base1 () {
echo 'this is base1 construct';
}
}
class class1 extends base1 {
function class1() {
$this -> base1();
echo 'this is class1 construct';
}
}
$c1 = new class1;
PHP5.x version:
PHP5.0 and above have greatly expanded the functions of the class. The constructor of a class is uniformly named __construct().
The constructor name of the subclass is also __construct() (also nonsense).
Whether the constructor of the parent class will be executed in the subclass, there are two situations:
1. If the subclass does not define the constructor __construct(), the constructor of the parent class will be inherited by default, and will be executed automatically.
2. If the subclass defines the constructor __construct(), because the constructor function name is also __construct(), the constructor of the subclass actually overrides the constructor of the parent class. What is executed at this time is the constructor of the subclass.
At this time, if you want to execute the constructor of the parent class in the subclass, you must execute a statement similar to the following:
parent::__construct();class base2 {
function __construct() {
echo 'this is base2 construct';
}
function __destruct() {}
}
class class2 extends base2 {
function __construct() {
parent::__construct();
echo 'this is class2 construct';
}
}
Note that the parent::__construct(); statement does not necessarily have to be placed in the constructor of the subclass. Placing it in the constructor of a subclass only ensures that it is automatically executed when the subclass is instantiated.
Compatibility issues between PHP4.0 and 5.0 class constructors:
In PHP5.0 and above, it is also compatible with the definition rules of constructors of version 4.0. If both the 4.0 constructor and the __construct() function are defined, the __construct() function takes precedence.
In order to make the class code compatible with both PHP4.0 and 5.0, the following method can be adopted:
class class3 { The above content is quoted from "Fried Peanuts" Brother, thank you for sharing.
The above introduces PHP object-oriented (OOP)-inheritance and compatibility of construction methods of different PHP versions, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.