PHP new static与new self

读TP6源码时,容器类中有一段代码如下:
/**
     * 获取当前容器的实例(单例)
     * @access public
     * @return static
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        if (static::$instance instanceof Closure) {
            return (static::$instance)();
        }

        return static::$instance;
    }
其中,new static这种用法平常不常用,其实是使用了静态延迟绑定,static不再被解析为定义当前方法所在的类,而是在实际运行时计算的。
现作比较new self与new static:
同:无继承时,两者用法没有区别
异:存在继承关系时,new self返回的实例是确定的,都返回同一个类的实例;new static返回的实例是由调用者决定的。

posted @ 2021-02-18 15:31  一步至遥  阅读(204)  评论(0编辑  收藏  举报
TOP