検索
ホームページphp教程php手册PHP parent调用父类构造函数

PHP parent调用父类构造函数

Jun 13, 2016 am 11:11 AM
parentphp関数存在する勉強私たち指向ポインタはい知る移行

大家在学习

我们知道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来调用。


声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。