首 先我們來理解三個關鍵字: 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
?>
我 們看,上面的類分別在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使用來指向類中的靜態變數。
<?php
class Counter
{
//定義屬性,包括一個靜態變數
private static $firstCount = 0;
private $lastCount;
//建構函式
function __construct()
{
$this->lastCount = ++selft::$firstCount; //使用self來調用靜態變數,使用self調用必須使用::(域運算子號)
}
//列印最次數值
function printLastCount()
{
print( $this->lastCount );
}
}
//執行個體化對象
$countObject = new Counter();
$countObject->printLastCount(); //輸出 1
?>
我 們這裡只要注意兩個地方,第6行和第12行。我們在第二行定義了一個靜態變數$firstCount,並且初始值為0,那麼在12行的時候調用了這個值 得,使用的是self來調用,並且中間使用"::"來串連,就是我們所謂的域運算子,那麼這時候我們調用的就是類自己定義的靜態變數$ frestCount,我們的靜態變數與下面對象的執行個體無關,它只是跟類有關,那麼我調用類本身的的,那麼我們就無法使用this來引用,可以使用 self來引用,因為self是指向類本身,與任何對象執行個體無關。換句話說,假如我們的類裡面靜態成員,我們也必須使用self來調用。
(3)parent
我們知道parent是指向父類的指標,一般我們使用parent來調用父類的建構函式。
<?php
//基類
class Animal
{
//基類的屬性
public $name; //名字
//基類的建構函式
public function __construct( $name )
{
$this->name = $name;
}
}
//衍生類別
class Person extends Animal //Person類繼承了Animal類
{
public $personSex; //性別
public $personAge; //年齡
//繼承類的建構函式
function __construct( $personSex, $personAge )
{
parent::__construct( "heiyeluren" ); //使用parent調用了父類的建構函式
$this->personSex = $personSex;
$this->personAge = $personAge;
}
function printPerson()
{
print( $this->name. " is " .$this->personSex. ",this year " .$this->personAge );
}
}
//執行個體化Person對象
$personObject = new Person( "male", "21");
//執行列印
$personObject->printPerson(); //輸出:heiyeluren is male,this year 21
?>
我 們注意這麼幾個細節:成員屬性都是public的,特別是父類的,是為了供繼承類通過this來訪問。我們注意關鍵的地方,第25行:parent:: __construct( "heiyeluren" ),這時候我們就使用parent來調用父類的建構函式進行對父類的初始化,因為父類的成員都是public的,於是我們就能夠在繼承類中直接使用 this來調用。