background image

么在语句②的时候使用了 self 调用这个值,那么这时候我们调用的就是类自己定义的静
态变量

$frestCount

。我们的静态变量与下面对象的实例无关,它只是跟类有关,那么我调

用类本身的的,那么我们就无法使用 this 来引用,因为 self 是指向类本身,与任何对象实
例无关。然后前面使用的 this 调用的是实例化的对象

$obj

,大家不要混淆了。

关于 self 就说到这里,结合例子还是比较方便理解的。第二篇结束。
 
{三}PHP 中 this,self,parent 的区别之三 parent 篇
此篇我们就 parent 的用法进行讲解。
首先,我们明确,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 对象