以前有人詢問self
關鍵字的用法,答案是比較明顯的:靜態成員函數內不能用this
調用非成員函數,但能夠用self
調用靜態成員函數/變量/常量;其餘成員函數能夠用self
調用靜態成員函數以及非靜態成員函數。隨着討論的深刻,發現self
並無那麼簡單。鑑於此,本文先對幾個關鍵字作對比和區分,再總結self
的用法。ide
parent
、 static
以及 this
的區別要想將完全搞懂 self
,要與 parent
、 static
以及 this
區分開。如下分別作對比。函數
parent
self
與 parent
的區分比較容易: parent
引用父類/基類被隱蓋的方法(或變量), self
則引用自身方法(或變量)。例如構造函數中調用父類構造函數:this
class Base { public function __construct() { echo "Base contructor!", PHP_EOL; } } class Child { public function __construct() { parent::__construct(); echo "Child contructor!", PHP_EOL; } } new Child; // 輸出: // Base contructor! // Child contructor!
static
static
常規用途是修飾函數或變量使其成爲類函數和類變量,也能夠修飾函數內變量延長其生命週期至整個應用程序的生命週期。可是其與 self
關聯上是PHP 5.3以來引入的新用途:靜態延遲綁定。spa
有了 static
的靜態延遲綁定功能,能夠在運行時動態肯定歸屬的類。例如:code
class Base { public function __construct() { echo "Base constructor!", PHP_EOL; } public static function getSelf() { return new self(); } public static function getInstance() { return new static(); } public function selfFoo() { return self::foo(); } public function staticFoo() { return static::foo(); } public function thisFoo() { return $this->foo(); } public function foo() { echo "Base Foo!", PHP_EOL; } } class Child extends Base { public function __construct() { echo "Child constructor!", PHP_EOL; } public function foo() { echo "Child Foo!", PHP_EOL; } } $base = Child::getSelf(); $child = Child::getInstance(); $child->selfFoo(); $child->staticFoo(); $child->thisFoo();
程序輸出結果以下:對象
Base constructor! Child constructor! Base Foo! Child Foo! Child Foo!
在函數引用上, self
與 static
的區別是:對於靜態成員函數, self
指向代碼當前類, static
指向調用類;對於非靜態成員函數, self
抑制多態,指向當前類的成員函數, static
等同於 this
,動態指向調用類的函數。blog
parent
、 self
、 static
三個關鍵字聯合在一塊兒看挺有意思,分別指向父類、當前類、子類,有點「過去、如今、將來」的味道。生命週期
this
self
與 this
是被討論最多,也是最容易引發誤用的組合。二者的主要區別以下:get
this
不能用在靜態成員函數中, self
能夠;self
,不要用 $this::
或 $this->
的形式;self
,只能用 this
;this
要在對象已經實例化的狀況下使用, self
沒有此限制;self
抑制多態行爲,引用當前類的函數;而 this
引用調用類的重寫(override)函數(若是有的話)。self
的用途看完與上述三個關鍵字的區別, self
的用途是否是呼之即出?一句話總結,那就是: self
老是指向「當前類(及類實例)」。詳細說則是:string
this
要加 $
符號且必須加,強迫症表示很難受;$this->
調用非靜態成員函數,可是能夠經過 self::
調用,且在調用函數中未使用 $this->
的狀況下還能順暢運行。此行爲貌似在不一樣PHP版本中表現不一樣,在當前的7.3中ok;self
,猜猜結果是什麼?都是 string(4) "self"
,迷之輸出;return $this instanceof static::class;
會有語法錯誤,可是如下兩種寫法就正常:$class = static::class;return $this instanceof $class;// 或者這樣:return $this instanceof static;