Everyone is learning
We know that PHP parent is a pointer to the parent class. Generally, we use parent to call the constructor of the parent class.
- < ?php
- //Base class
- class Animal
- {
- //Attributes of base class
- public $name; //Name
- //Constructor of base class
- public function __construct( $name )
- {
- $this->name = $name;
- }
- }
- //Derived class
- class Person extends Animal
- //The Person class inherits the Animal class
- {
- public $personSex; //Gender
- public $personAge; //Age
- //Constructor of inherited class
- function __construct( $personSex ,
$personAge ) - {
- parent::__construct( "heiyeluren" );
//Use parent call The constructor of the parent class -
$this-> personSex = $personSex;
-
$this->personAge = $personAge;
- }
- function printPerson( )
- {
-
print( $this->name. " is " .$this->
personSex. ",this year " .$this->
personAge );
- }
- }
- //Instantiate Person object
-
$personObject = new Person( "male", "21");
- //Perform printing
-
$personObject->printPerson();
- //Output: heiyeluren is male, this year 21
-
?>
We pay attention to these few details: member attributes are all public, especially those of the parent class. It is for inherited classes to access through this. We pay attention to the key point, line 25: parent:: __construct( "heiyeluren" ). At this time, we use PHP parent to call the constructor of the parent class to initialize the parent class, because the members of the parent class are all public. , so we can directly use this to call in the inherited class.
http://www.bkjia.com/PHPjc/445967.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445967.htmlTechArticleEveryone is studying. We know that PHP parent is a pointer to the parent class. Generally, we use parent to call the structure of the parent class. function. ?php //Base class classAnimal { //Attributes of base class public$name...