大家在学习PHP语言的时候,都会对与指针相关的内容感到特别的头疼。很难理解并不代表不用了解。下面我们就来看看PHP parent是如何指向父类指针的。#t#

我们知道PHP parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。
- < ?php  
- //基类  
- class Animal  
- {  
- //基类的属性  
- public $name; //名字  
- //基类的构造函数  
- public function __construct( $name )  
- {  
- $this->name = $name;  
- }  
- }  
- //派生类  
- class Person extends Animal   
- //Person类继承了Animal类  
- {  
- public $personSex; //性别  
- public $personAge; //年龄  
- //继承类的构造函数  
- function __construct( $personSex, 
 $personAge )
- {  
- parent::__construct( "heiyeluren" );
 //使用parent调用了父类的构造函数
- $this->personSex = $personSex;  
- $this->personAge = $personAge;  
- }  
- function printPerson()  
- {  
- print( $this->name. " is " .$this->
 personSex. ",this year " .$this->
 personAge );
- }  
- }  
- //实例化Person对象  
- $personObject = new Person( "male", "21");  
- //执行打印  
- $personObject->printPerson();   
- //输出:heiyeluren is male,this year 21  
- ?>  
我们注意这么几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。我们注意关键的地方,第25行:parent:: __construct( "heiyeluren" ),这时候我们就使用PHP parent来调用父类的构造函数进行对父类的初始化,因为父类的成员都是public的,于是我们就能够在继承类中直接使用 this来调用。
            
            网站名称:PHPparent调用父类构造函数            
            URL标题:
http://cdxtjz.cn/article/dhsecsd.html