PHP5的72變:理解this,self和parent關鍵字--第2變

今天理解一下PHP5的這三個關鍵字: this,self,parent

從字面上比較好理解,是指這,自己,父親。我們先建立幾個概念,這三個關鍵字分別是用在什麼地方呢?

我們初步解釋一下:

        this是指向當前對象的指針(我們姑且用C裏面的指針來看吧,其實也可以看成引用),   

        self是指向當前類的指針,

        parent是指向父類的指針。


我們這裏頻繁使用指針來描述吧,是因爲沒有更好的語言來表達,那我們就根據實際的例子結合來講講。

(1) this

<?php
class UserName
{ 
//定義屬性 
private $name;
//定義構造函數
function __construct( $name )
{
$this->name = $name; //這裏已經使用了this指針
}
//析構函數
function __destruct(){}
//打印用戶名成員函數
function printName()
{
print( $this->name ); //又使用了this指針
}
}
//實例化對象
$nameObject = new UserName( "heiyeluren" );
//執行打印
$nameObject->printName(); //輸出: heiyeluren
//第二次實例化對象
$nameObject2 = new UserName( "PHP5" );
//執行打印
$nameObject2->printName(); //輸出:PHP5
?>

我們看,上面的類分別在9行和16行使用了this指針,那麼當時this是指向誰呢?其實this是在實例化的時候來確定指向誰,比如第一次實例化對象的時候(20行),那麼當時this就是指向$nameObject對象,那麼執行16行的打印的時候就把print( $this->name )變成了print( $nameObject->name ),那麼當然就輸出了"heiyeluren"。第二個實例的時候,print( $this->name )變成了print( $nameObject2->name ),於是就輸出了"PHP5"。所以說,this就是指向當前對象實例的指針,不指向任何其他對象或類。


(2)self
首先我們要明確一點,self是指向類本身,也就是self是不指向任何已經實例化的對象,一般self使用來指向類中的靜態變量。
1 <?php
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()
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 <?php
2
3 //基類
4 class Animal
5 {
6 //基類的屬性
7 public $name; //名字
8
9 //基類的構造函數
10 public function __construct( $name )
11 {
12 $this->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是對父類的引用。

未完待續。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章