Home  >  Article  >  Backend Development  >  How to call the constructor method of the parent class in PHP

How to call the constructor method of the parent class in PHP

王林
王林Original
2020-07-10 15:39:174562browse

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()].

How to call the constructor method of the parent class in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn