Home  >  Article  >  Backend Development  >  PHP parent calls parent class constructor_PHP tutorial

PHP parent calls parent class constructor_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:34:391710browse

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.

  1. < ?php
  2. //Base class
  3. class Animal
  4. {
  5. //Attributes of base class
  6. public $name; //Name
  7. //Constructor of base class
  8. public function __construct( $name )
  9. {
  10. $this->name = $name;
  11. }
  12. }
  13. //Derived class
  14. class Person extends Animal
  15. //The Person class inherits the Animal class
  16. {
  17. public $personSex; //Gender
  18. public $personAge; //Age
  19. //Constructor of inherited class
  20. function __construct( $personSex ,
    $personAge )
  21. {
  22. parent::__construct( "heiyeluren" );
    //Use parent call The constructor of the parent class
  23. $this-> personSex = $personSex;
  24. $this->personAge = $personAge;
  25. }
  26. function printPerson( )
  27. {
  28. print( $this->name. " is " .$this->
    personSex. ",this year " .$this->
    personAge );
  29. }
  30. }
  31. //Instantiate Person object
  32. $personObject = new Person( "male", "21");
  33. //Perform printing
  34. $personObject->printPerson();
  35. //Output: heiyeluren is male, this year 21
  36. ?>

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.


www.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...
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