Home > Article > Backend Development > How to call the constructor method of the parent class in PHP
The way a subclass in php calls the constructor of the parent class is: It can be achieved through the parent keyword. parent is a pointer to the parent class, which essentially represents the class of the parent class, not the object of the parent class. The specific calling method is: [parent::__construct()].
parent is a pointer to the parent class, which essentially represents the "class" of the parent class, not the "object" of the parent class.
(Recommended tutorial: php tutorial)
Generally we use parent to call the constructor of the parent class, such as parent::__construct() means calling the parent class's constructor __construct() method (constructor method).
Code implementation:
/* * 子类使用父类中的构造方法。 */ //父类方法 class Person { //父类中的构造方法 function __construct(){ echo '这是父类中的构造方法!'; } } //子类方法(继承子父类) class MenPerson extends Person { //子类重的构造方法 function __construct(){ //调用父类中的构造方法 parent::__construct(); //调用过之后在继续调用其下的各种实现 echo '这是子类中的构造方法!'; } } //实例化子类对象 $menp = new MenPerson();
The above is the detailed content of How to call the constructor method of the parent class in PHP. For more information, please follow other related articles on the PHP Chinese website!