PHP parent調(diào)用父類構(gòu)造函數(shù)
大家在學(xué)習(xí)PHP語言的時候,都會對與指針相關(guān)的內(nèi)容感到特別的頭疼。很難理解并不代表不用了解。下面我們就來看看PHP parent是如何指向父類指針的。#t#
我們知道PHP parent是指向父類的指針,一般我們使用parent來調(diào)用父類的構(gòu)造函數(shù)。
- < ?php
- //基類
- class Animal
- {
- //基類的屬性
- public $name; //名字
- //基類的構(gòu)造函數(shù)
- public function __construct( $name )
- {
- $this->name = $name;
- }
- }
- //派生類
- class Person extends Animal
- //Person類繼承了Animal類
- {
- public $personSex; //性別
- public $personAge; //年齡
- //繼承類的構(gòu)造函數(shù)
- function __construct( $personSex,
$personAge ) - {
- parent::__construct( "heiyeluren" );
//使用parent調(diào)用了父類的構(gòu)造函數(shù) - $this->personSex = $personSex;
- $this->personAge = $personAge;
- }
- function printPerson()
- {
- print( $this->name. " is " .$this->
personSex. ",this year " .$this->
personAge ); - }
- }
- //實(shí)例化Person對象
- $personObject = new Person( "male", "21");
- //執(zhí)行打印
- $personObject->printPerson();
- //輸出:heiyeluren is male,this year 21
- ?>
我們注意這么幾個細(xì)節(jié):成員屬性都是public的,特別是父類的,是為了供繼承類通過this來訪問。我們注意關(guān)鍵的地方,第25行:parent:: __construct( "heiyeluren" ),這時候我們就使用PHP parent來調(diào)用父類的構(gòu)造函數(shù)進(jìn)行對父類的初始化,因?yàn)楦割惖某蓡T都是public的,于是我們就能夠在繼承類中直接使用 this來調(diào)用。