PHP parent调用父类构造函数_PHP教程

WBOY
Freigeben: 2016-07-15 13:34:39
Original
1687 Leute haben es durchsucht

大家在学习

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


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445967.htmlTechArticle大家在学习 我们知道PHP parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。 ?php //基类 classAnimal { //基类的属性 public$name...
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!