get_called_class()和static :: class之间的区别

What is the difference between calling get_called_class() and static::class inside a static class method?

For example:

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'

It appears to work the same in both cases but there may be some nuances I should be aware of.

展开翻译

译文

调用 get_called_class()</ code>和 static :: class之间的区别是什么? </ code>在静态类方法中?</ p>

例如:</ p>

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

公共静态函数bar()
{
return get_called_class();
}
}

class Child extends Base {}

echo Base :: foo(); //打印'Base'
echo Base :: bar(); //打印'Base'
echo Child :: foo(); //打印'Child'
echo Child :: bar(); //打印'儿童'
</ code> </ pre>

在这两种情况下看起来都是一样的,但我可能会注意到一些细微差别。</ p>
</ DIV>

1个回答

static::class was "only" added in PHP 5.5, but other than that they should work identically.

From a quick test, static::class appears to be slightly faster. Using the code from the question:

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();});

Parent, static::class took 0.0467 seconds

Parent, get_called_class took 0.0559 seconds

Child, static::class took 0.0468 seconds

Child, get_called_class took 0.0554 seconds

But you've got to be doing well into six-figures worth of iterations to notice. See https://3v4l.org/qaXln (3v4l definitely isn't the best tool for benchmarking, but there's enough of a pattern)

展开翻译

译文



static :: class </ code> 在PHP 5.5中添加了”仅“,但除此之外,它们的工作方式相同。</ p>

来自 快速测试, static :: class </ code>似乎稍微快一些。 使用问题中的代码:</ p>

  profile(“Parent,static :: class”,function(){Base :: foo();}); 
nofofile(“ Parent,get_called_class“,function(){Base :: bar();});
profile(”Child,static :: class“,function(){Child :: foo();});
nofofile(”Child ,get_called_class“,function(){Child :: bar();});
</ code> </ pre>


Parent,static :: class耗时0.0467秒< / p>

Parent,get_called_class花了0.0559秒</ p>

Child,static :: class花了0.0468秒</ p>

Child,get_called_class 耗时0.0554秒</ p>
</ blockquote>

但是你必须做好六位数的迭代才能注意到。 请参阅 https://3v4l.org/qaXln (3v4l绝对不是基准测试的最佳工具,但有 足够的模式)</ p>
</ div>

douao1959
douao1959 是的,确切地说。 返回并更改旧代码是不够的改进,但新代码也可能使用稍快的版本。 至少在我看来,它也更好一些。
一年多之前 回复
doudou8081
doudou8081 因此,假设static :: class稍快一些,并且与get_called_class的工作方式相同,那么在现代应用程序中没有理由使用后者吗?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问