日期:2014-05-17  浏览次数:20408 次

PHP理解之一:this,self,parent三个关键字之间的区别【转】

转自:http://hi.baidu.com/sneidar/blog/item/4c0015ecd4da9d38269791d3.html

?

PHP5是一具备了大部分面向对象语言的特性的语言,比PHP4有了很多的面向对象的特性,但是有部分概念也比较难以理解,这里我主要谈的是 this,self,parent三个关键字之间的区别。从字面上比较好理解,分别是指这、自己、父亲。我们先建立几个概念,这三个关键字分别是用在什么 地方呢?我们初步解释一下,

  • this是指向当前对象的指针(姑且用C里面的指针来看吧);
  • self是指向当前类的指针;
  • parent是指向父类的指针

我们这里频繁使用指针来描述,是因为没有更好的语言来表达。

?

一、this:当前对象指针

 class UserName {
 	private $name;

 	function __construct($name){
 		$this->name = $name;
 	}

    function __destruct(){

    }

    function printName(){
    	print($this->name);
    }
 }

 $no1 = new UserName('thomas.chen');
 $no1->printName();
 print('<br/>');
 $no2 = new UserName('berry.chen');
 $no2->printName();

?

我们看,上面的类分别在5行和13行使用了this指针,那么当时this是指向谁呢?其实this是在实例化的时候来确定指向谁,比如第一次实例化对象 的时候(17行),那么当时this就是指向$no1t对象,那么执行18行的打印的时候就把print( $this->name )变成了print( $nameObject->name ),那么当然就输出了"thomas.chen"。第二个实例的时候,print( $this->name )变成了print( $no2->name ),于是就输出了"berry.chen"。所以说,this就是指向当前对象实例的指针,不指向任何其他对象或类。

?

?

二、self:当前类指针

class Counter {
	private static $firstCount = 0;
	private $lastCount;

	function __construct() {
		$this->lastCount = ++self :: $firstCount;
	}

	function printLastCount(){
		print($this->lastCount);
	}
}

$c1 = new Counter();
$c1->printLastCount();
print('<br/>');
$c2 = new Counter();
$c2->printLastCount();

?

我们这里只要注意两个地方,第2行和第6行。我们在第2行定义了一个静态变量$firstCount,并且初始值为0,那么在6行的时候调用了这个值, 使用的是self来调用,并且中间使用"::"来连接,就是我们所谓的域运算符,那么这时候我们调用的就是类自己定义的静态变量$frestCount, 我们的静态变量与下面对象的实例无关,它只是跟类有关,那么我调用类本身的的,那么我们就无法使用this来引用,可以使用self来引用,因为self是指向类本身,与任何对象实例无关。换句话说,假如我们的类里面静态的成员,我们也必须使用self来调用。

?

?

三、parent : 父指针。通常一般我们使用parent来调用父类的构造函数。

class Animal {
	public $name;

	function __construct($name){
		$this->name = $name;
	}

}

class Person extends Animal {
	public $sex;
	public $age;

	function __construct($name,$sex,$age){
		parent::__construct($name);
		$this->sex = $sex;
		$this->age = $age;
	}

	function printPerson(){
		print('[name:'.$this->name.', sex:'.$this->sex.', age:'.$this->age.']');
	}
}

$person = new Person('thomas.chen','Male','25');
$person->printPerson();

?

我 们注意这么几个细节:成员属性都是public的,特别是父类的,是为了供继承类通过this来访问。我们注意关键的地方,第15行: parent::__construct($name),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,因为父类的成员都是public的,于是我们就能够在继承类中直接使用 this来调用。

?

?