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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章