//构造函数
function __construct()
{
$this->lastCount = ++self::$firstCount; //使用self来调用静态变量 语句②
}
//打印lastCount数值
function printLastCount()
{
print( $this->lastCount );
}
}
//实例化对象
$obj = new Counter();
$obj->printLastCount(); //执行到这里的时候,程序输出 1
?>
这里要注意两个地方语句①和语句②。我们在语句①定义了一个静态变量$firstCount,那么在语句②的时候使用了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对象
$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。
总结:this是指向对象实例的一个指针,在实例化的时候来确定指向;self是对类本身的一个引用,一般用来指向类中的静态变量;parent是对父类的引用,一般使用parent来调用父类的构造函数。







