PHP:get_Called_class() 与 get_class($this)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16515516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:16:37  来源:igfitidea点击:

PHP: get_called_class() vs get_class($this)

phpoop

提问by sebataz

In PHP what is the difference between get_called_class()and get_class($this)when used inside an instance?

在 PHP 中get_called_class()get_class($this)在实例中使用时有什么区别?

Example:

例子:

class A {
    function dump() {
        echo get_called_class();
        echo get_class($this);
    }
}

class B extends A {}

$A = new A();
$B = new B();

$A->dump(); // output is 'AA'
$B->dump(); // output is 'BB'

Is there any difference in this case?

在这种情况下有什么区别吗?

When should I be using one or the other get_called_class()or get_class($this)?

我什么时候应该使用一个或另一个get_called_class()get_class($this)

回答by Ja?ck

In this case there's no difference, because $thisalways points to the correct instance from which the class name is resolved using get_class().

在这种情况下没有区别,因为$this总是指向正确的实例,使用get_class().

The function get_called_class()is intended for static methods. When static methods are overridden, this function will return the class name that provides the context for the current method that's being called.

该函数get_called_class()用于静态方法。当静态方法被覆盖时,此函数将返回为当前调用的方法提供上下文的类名。

回答by Michael Zabka

For much faster alternative of get_called_class()in PHP >= 5.5, use static::class. It works to get the top level class for static method calls, as well as for inherited methods.

get_called_class()在 PHP >= 5.5 中更快地替代,请使用static::class. 它用于获取静态方法调用以及继承方法的顶级类。

回答by Orangepill

Not in this case... if dump was a static method and eliminate the $thisparameter then get_class would return "A" in both cases and get_called_class would return "B" when you did B::dump();

在这种情况下不是......如果 dump 是一个静态方法并消除了$this参数,那么 get_class 在这两种情况下都会返回“A”,而当你这样做时 get_Called_class 会返回“B”B::dump();

回答by Dr.Kameleon

The answer, in this particular case, is : NO.

在这种特殊情况下,答案是:NO

There is no difference.

没有区别。



Reference :(http://php.net/manual/en/function.get-class.php)

参考:http://php.net/manual/en/function.get-class.php

string get_class ([ object $object = NULL ] )

...

If object is omitted when inside a class, the name of that class is returned.

字符串 get_class ([ object $object = NULL ] )

...

如果在类中省略 object,则返回该类的名称。

回答by Eddie Jaoude

In this instance there is no difference, both return the name of the class, but the get_called _class has Late Static Binding

在这个实例中没有区别,都返回类的名称,但是 get_called _class 具有 Late Static Binding