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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值