【问题标题】:Difference between get_called_class() and static::classget_call_class() 和 static::class 之间的区别
【发布时间】:2018-11-02 09:48:36
【问题描述】:

在静态类方法中调用get_called_class()static::class 有什么区别?

例如:

class Base
{
    public static function foo()
    {
        return static::class;
    }

    public static function bar()
    {
        return get_called_class();
    }
}

class Child extends Base {}

echo Base::foo();  // prints 'Base'
echo Base::bar();  // prints 'Base'
echo Child::foo(); // prints 'Child'
echo Child::bar(); // prints 'Child'

这两种情况似乎都一样,但我应该注意一些细微差别。

【问题讨论】:

    标签: php class static


    【解决方案1】:

    static::classwas "only" added in PHP 5.5,但除此之外它们应该工作相同。

    通过快速测试,static::class 似乎稍快一些。使用问题中的代码:

    profile("Parent, static::class", function () { Base::foo();});
    profile("Parent, get_called_class", function () { Base::bar();});
    profile("Child, static::class", function () { Child::foo();});
    profile("Child, get_called_class", function () { Child::bar();});
    

    父级,static::class 耗时 0.0467 秒

    父级,get_call_class 耗时 0.0559 秒

    孩子,static::class 耗时 0.0468 秒

    孩子,get_call_class 耗时 0.0554 秒

    但是你必须在六位数的迭代中做得很好才能注意到。见https://3v4l.org/qaXln(3v4l 绝对不是基准测试的最佳工具,但有足够的模式)

    【讨论】:

    • 那么鉴于static::class 稍微快一点并且工作方式与get_called_class 相同,那么没有理由在现代应用程序中使用后者?
    • @KubaSzymanowski 是的,没错。回过头来修改旧代码还不够改进,新代码还不如使用稍微快一点的版本。至少在我看来,它也更好一些。
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2012-01-13
    • 1970-01-01
    • 2014-01-31
    • 2016-04-13
    • 2011-06-09
    相关资源
    最近更新 更多