PHPnewself()和newstatic()的区别

原创
小哥 2年前 (2023-05-17) 阅读数 19 #PHP

使用self::或者__CLASS__对当前类的静态引用,取决于定义当前方法所在的类:使用 static:: 不再被解析为定义当前方法所在的类,而是在实际运行时计算的。也可以称之为“静态绑定”,因为它可以用于(但不限于)静态方法的调用。

class Father
{
    /**
     * @return Father
     */
    public static function getSelf()
    {
        return new self();
    }

    /**
     * @return static
     */
    public static function getStatic()
    {
        return new static();
    }
}

class Son extends Father
{
}

echo get_class(Son::getSelf()); // Father
echo get_class(Son::getStatic()); // Son
echo get_class(Father::getSelf()); // Father
echo get_class(Father::getStatic()); // Father

这里面注意这一行 get_class(Son::getStatic()); 返回的是 Son 这个 class,可以总结如下:

new self
1.self返回的是 new self 中关键字 new 所在的类中,比如这里例子的 :

public static function getSelf()
{
    return new self(); // new 关键字在 Father 这里
}

始终返回 Father。

new static
2.static 则上面的基础上,更聪明一点点:static 会返回执行 new static() 的类,比如 Son 执行 get_class(Son::getStatic()) 返回的是 Son, Father 执行 get_class(Father::getStatic()) 返回的是 Father

而在没有继承的情况下,可以认为 new self 和 new static是返回相同的结果。

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

上一篇:MySQL前缀索引 下一篇:数据库ER图