The three different versions represent the evolution of PHP handling of static. The earliest one get_class
was insufficient to handle scenarios where you needed to distinguish the class as called and the class as defined. Here is an example
So, get_called_class
was introduced in PHP 5.3 to resolve the ambiguity. That lasted quite a while, and is still a valid choice, but now we have the pseudo selector ::class
. Why?
The pseudo selector provides two nice benefits. The first is that it allows you to replace string class names with compile-time checking of namespace rules. Compare:
namespace Foo\Bar;
class Baz { public static function hi($name) { echo "Hi, $name!"; } }
call_user_func([ Baz::class, 'hi' ], 'bishop');
with:
call_user_func([ '\Foo\Bar\Baz', 'hi' ], 'bishop');
If I fat finger that last one, mistyping it, that will be a run-time error:
call_user_func([ '\Foo\Bar\Bza', 'hi' ], 'bishop'); // error at runtime!
But using the ::class
pseudo I get compile-time checking:
call_user_func([ Bza::class, 'hi' ], 'bishop'); // error at compile-time!
I realize in an interpreted language the distinction between compile-time and run-time is thin, but it does matter when it comes to performance. And that's the second benefit: ::class
is more performant.