PHP中new static()與new self()

先看一段簡單的代碼

<?php 
abstract class A {

    public function __construct()
    {
        echo "obj is ";
    }
    public static function static_create()
    {
        return new static();
    }

    public static function self_create()
    {
        return new self();
    }
}

class B extends A {}
class C extends A {}

C::self_create();
$obj = C::static_create();
echo get_class($obj);

 ?>

運行後出現
Fatal error: Cannot instantiate abstract class A in D:\www\test\static.php on line 16
不能實例化抽象類
大家知道self這個關鍵字,其實就是指當前類的引用,儘管是它的具體子類C去調用這個方法。self被解析爲實例化A,而不是解析爲實例化C,因此,self的方法是不可行的。

當然我們有解決方法
在php > 5.3引入了延遲靜態綁定的概念,用static關鍵字標明,注意下面斜體的英文

self refers to the same class whose method the new operation takes place in.
static in PHP 5.3’s late static bindings refers to whatever class in the hierarchy which you call the method on.
In the following example, B inherits both methods from A. self is bound to A because it’s defined in A’s implementation of the first method, whereas static is bound to the called class (also see get_called_class() ).

new staitc()代表將會實例化調用它方法的那個類,有點像工廠模式多態的感覺,當然,static確實是工廠模式中必不可少的~

將 C::self_create(); 註釋掉,再次運行,瀏覽器顯示 obj is C

發佈了22 篇原創文章 · 獲贊 37 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章