PHP: get_called_class() vs get_class($this)

2019-03-17 20:38发布

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

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)?

标签: php oop
5条回答
够拽才男人
2楼-- · 2019-03-17 20:53

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

There is no difference.


Reference : (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.

查看更多
SAY GOODBYE
3楼-- · 2019-03-17 20:58

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

查看更多
再贱就再见
4楼-- · 2019-03-17 21:00

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.

查看更多
我只想做你的唯一
5楼-- · 2019-03-17 21:04

In this case there's no difference, because $this always points to the correct instance from which the class name is resolved using 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.

查看更多
▲ chillily
6楼-- · 2019-03-17 21:13

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

查看更多
登录 后发表回答