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('
'); $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('
');$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來調用。
?
?