您的位置:首页 > 编程语言 > PHP开发

PHP中this,self,parent的区别之三parent篇

2012-11-29 18:21 531 查看
首先,我们明确,parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。实例如下:
<?php
//建立基类Animal
class Animal
{
public $name; //基类的属性,名字$name

//基类的构造函数,初始化赋值
public function __construct( $name )
{
$this->name = $name;
}
}

//定义派生类Person 继承自Animal类
class Person extends Animal
{
public$personSex;       //对于派生类,新定义了属性$personSex性别、$personAge年龄
public $personAge;

//派生类的构造函数
function __construct( $personSex, $personAge )
{
parent::__construct( "PBPHome");    //使用parent调用了父类的构造函数 语句①
$this->personSex = $personSex;
$this->personAge = $personAge;
}

//派生类的成员函数,用于打印,格式:名字 is name,age is 年龄
function printPerson()
{
print( $this->name. " is ".$this->personSex. ",age is ".$this->personAge );
}
}

//实例化Person对象
$personObject = new Person( "male", "21");

//执行打印
$personObject->printPerson();//输出结果:PBPHome is male,age is 21

?>
里面同样含有this的用法,大家自己分析。我们注意这么个细节:成员属性都是public(公有属性和方法,类内部和外部的代码均可访问)的,特别是父类的,这是为了供继承类通过this来访问。关键点在语句①:parent::__construct( "heiyeluren"),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,这样,继承类的对象就都给赋值了name为PBPHome。我们可以测试下,再实例化一个对象$personObject1,执行打印后name仍然是PBPHome。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: