Heim  >  Artikel  >  Backend-Entwicklung  >  PHP5中的this,self和parent关键字详解_PHP教程

PHP5中的this,self和parent关键字详解_PHP教程

WBOY
WBOYOriginal
2016-07-13 17:33:25735Durchsuche

php(做为现在的主流开发语言)5是一具备了大部分面向对象语言的特性的语言,比php(做为现在的主流开发语言)4有了很多的面向对象的特性,但是有部分概念也比较绕人,所以今天拿出来说说,说的不好,请高手见谅. (阅读本文,需要了解php(做为现在的主流开发语言)5的面向对象的知识)

首先我们来明白上面三个关键字: this,self,parent,从字面上比较好理解,是指这,自己,父亲,呵呵,比较好玩了,我们先建立几个概念,这三个关键字分别是用在什么地方呢?我们初步解释一下,this是指向当前对象的指针(我们姑且用C里面的指针来看吧),self是指向当前类的指针,parent是指向父类的指针。我们这里频繁使用指针来描述,是因为没有更好的语言来表达,呵呵,语文没学好。 -_-#

这么说还不能很了解,那我们就根据实际的例子结合来讲讲。


(1) this

1 (做为现在的主流开发语言)
2
3 class UserName
4 {
5     //定义属性   
6     private $name;
7
8     //定义构造函数
9     function __construct( $name )
10     {
11          $this->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( "php(做为现在的主流开发语言)5" );
32
33 //执行打印
34 $nameObject2->printName(); //输出:php(做为现在的主流开发语言)5
35 ?>

我们看,上面的类分别在11行和20行使用了this指针,那么当时this是指向谁呢?其实this是在实例化的时候来确定指向谁,比如第一次实例化对象的时候(25行),那么当时this就是指向$nameObject对象,那么执行18行的打印的时候就把print( $this->name ),那么当然就输出了"heiyeluren"。第二个实例的时候,print( $this->name )变成了print( $nameObject2->name ),于是就输出了"php(做为现在的主流开发语言)5"。所以说,this就是指向当前对象实例的指针,不指向任何其他对象或类。

 

(2)self

首先我们要明确一点,self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量。

1 (做为现在的主流开发语言)
2
3     class Counter
4     {
5         //定义属性,包括一个静态变量
6         private static $firstCount = 0;
7         private $lastCount;
8
9         //构造函数
10         function __construct()
11         {
12              $this->lastCount = ++selft::$firstCount; //使用self来调用静态变量,使用self调用必须使用::(域运算符号)
13         }
14
15         //打印最次数值
16         function printLastCount()

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/508642.htmlTechArticlephp (做为现在的主流开发语言) 5是一具备了大部分面向对象语言的特性的语言,比php (做为现在的主流开发语言) 4有了很多的面向对象的特性...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn