1
2
3 //基类
4 class Animal
5 {
6 //基类的属性
7 public $name; //名字
8
9 //基类的构造函数
10 public function __construct( $name )
11 {
12 $this->name = $name;
13 }
14 }
15
16 //派生类
17 class Person extends Animal //Person类继承了Animal类
18 {
19 public $personSex; //性别
20 public $personAge; //年龄
21
22 //继承类的构造函数
23 function __construct( $personSex, $personAge )
24 {
25 parent::__construct( "heiyeluren" ); //使用parent调用了父类的构造函数
26 $this->personSex = $personSex;
27 $this->personAge = $personAge;
28 }
29
30 function printPerson()
31 {
32 print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );
33 }
34 }
35
36 //实例化Person对象
37 $personObject = new Person( "male", "21");
38
39 //执行打印
40 $personObject->printPerson(); //输出:heiyeluren is male,this year 21
41
42 ?>
我 们注意这么几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。
我们注意关键的地方,第25行: parent::__construct( "heiyeluren" ),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,
因为父类的成员都是public的,于是我们就能够在继承类中直接使用 this来调用。
总结:
this是指向对象实例的一个指针,self是对类本身的一个引用,parent是对父类的引用。
转载自:http://blog.csdn.net/skynet001/article/details/7518164
以上就介绍了php中this,self,parent三个关键字的区分和对比,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。