您好,欢迎访问一九零五行业门户网

php中this,self,parent三个关键字的区分和对比

this,self,parent三个关键字从字面上比较好理解,分别是指这、自己、父亲。
this是指向当前对象的指针(姑且用c里面的指针来看吧)
self是指向当前类的指针
parent是指向父类的指针(我 们这里频繁使用指针来描述,是因为没有更好的语言来表达)
根据实际的例子来看看
(1) this
1 name = $name; //这里已经使用了this指针
12     }
13 
14     //析构函数
15     function __destruct(){}
16
17     //打印用户名成员函数
18     function printname()
19     {
20          print( $this->name ); //又使用了this指针
21     }
22 }
23
24 //实例化对象
25 $nameobject = new username( heiyeluren );
26
27 //执行打印
28 $nameobject->printname(); //输出: heiyeluren
29
30 //第二次实例化对象
31 $nameobject2 = new username( php5 );
32
33 //执行打印
34 $nameobject2->printname(); //输出:php5
35 ?>
我 们看,上面的类分别在11行和20行使用了this指针,那么当时this是指向谁呢?
其实this是在实例化的时候来确定指向谁,比如第一次实例化对象 的时候(25行),
那么当时this就是指向$nameobject对象,那么执行18行的打印的时候就把print( $this->name )变成了print( $nameobject->name ),那么当然就输出了heiyeluren。
第二个实例的时候,print( $this- >name )变成了print( $nameobject2->name ),于是就输出了php5。
所以说,this就是指向当前对象实例的指针,不指向任何其他对象或类。
(2)self
首先我们要明确一点,self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量。
1 lastcount = ++selft::$firstcount; //使用self来调用静态变量,使用self调用必须使用::(域运算符号)
13         }
14
15         //打印最次数值
16         function printlastcount()
17         {
18              print( $this->lastcount );
19         } 
20     }
21
22 //实例化对象
23 $countobject = new counter();
24
25 $countobject->printlastcount(); //输出 1
26
27 ?>
我 们这里只要注意两个地方,第6行和第12行。
我们在第二行定义了一个静态变量$firstcount,并且初始值为0,那么在12行的时候调用了这个值, 使用的是self来调用,并且中间使用::来连接,
就是我们所谓的域运算符,那么这时候我们调用的就是类自己定义的静态变量$frestcount, 我们的静态变量与下面对象的实例无关,它只是跟类有关,
那么我调用类本身的的,那么我们就无法使用this来引用,可以使用 self来引用,
因为self是指向类本身,与任何对象实例无关。换句话说,假如我们的类里面静态的成员,我们也必须使用self来调用。
(3)parent
我们知道parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。
1 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教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息