PHP parent calls the parent class Constructor

Source: Internet
Author: User

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 the base class
  6. Public $ name; // name
  7. // Constructor of the 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 the inherited class
  20. Function _ construct ($ personSex,
    $ PersonAge)
  21. {
  22. Parent: :__ construct ("heiyeluren ");
    // Use parent to 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 the Person object
  32. $ PersonObject = new Person ("male", "21 ");
  33. // Execute print
  34. $ PersonObject->PrintPerson ();
  35. // Output: heiyeluren is male, this year 21
  36. ?>

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.