PHP parent調用父類建構函式_PHP教程

來源:互聯網
上載者:User
大家在學習

我們知道PHP parent是指向父類的指標,一般我們使用parent來調用父類的建構函式。

  1. < ?php
  2. //基類
  3. class Animal
  4. {
  5. //基類的屬性
  6. public $name; //名字
  7. //基類的建構函式
  8. public function __construct( $name )
  9. {
  10. $this->name = $name;
  11. }
  12. }
  13. //衍生類別
  14. class Person extends Animal
  15. //Person類繼承了Animal類
  16. {
  17. public $personSex; //性別
  18. public $personAge; //年齡
  19. //繼承類的建構函式
  20. function __construct( $personSex,
    $personAge )
  21. {
  22. parent::__construct( "heiyeluren" );
    //使用parent調用了父類的建構函式
  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. //執行個體化Person對象
  32. $personObject = new Person( "male", "21");
  33. //執行列印
  34. $personObject->printPerson();
  35. //輸出:heiyeluren is male,this year 21
  36. ?>

我們注意這麼幾個細節:成員屬性都是public的,特別是父類的,是為了供繼承類通過this來訪問。我們注意關鍵的地方,第25行:parent:: __construct( "heiyeluren" ),這時候我們就使用PHP parent來調用父類的建構函式進行對父類的初始化,因為父類的成員都是public的,於是我們就能夠在繼承類中直接使用 this來調用。


http://www.bkjia.com/PHPjc/445967.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/445967.htmlTechArticle大家在學習 我們知道PHP parent是指向父類的指標,一般我們使用parent來調用父類的建構函式。 ?php //基類 classAnimal { //基類的屬性 public$name...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.