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 the base class
- Public $ name; // name
- // Constructor of the 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 the inherited class
- Function _ construct ($ personSex,
$ PersonAge)
- {
- Parent: :__ construct ("heiyeluren ");
// Use parent to 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 the Person object
- $ PersonObject = new Person ("male", "21 ");
- // Execute print
- $ PersonObject->PrintPerson ();
- // Output: heiyeluren is male, this year 21
- ?>
We should pay attention to the following details: the member attributes are all public, especially the parent class, to be accessed by the inheritance class through this. Note the key points. Row 25th: parent: _ construct ("heiyeluren "), at this time, we will 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, therefore, we can directly use this to call the inheritance class.