PHP 5.5 Class Name Resolution

PHP 5.5 introduced as a new function a new way to get the class name through the syntax ::class :

 <?php namespace Testing; class Test{} echo Test::class; // Testing\Test; 

It works fine, okay? BUt, about which I and other friends wanted to know why this syntax also returns the class name when used next to an undeclared class. For example:.

 <?php echo UndeclaredClass::class; // UndeclaredClass 

In several other cases, an error occurs, but not here. Does anyone know, if possible, a concrete basis, why is this happening?

Does it have anything for late static bindings or just a (temporary) limitation / error of this new function?

+8
php class
source share
2 answers

Finally, the official answer is ... relatively speaking. It was introduced to me by someone identified by requinix@php.net in the bu report that I created today. The only exception is how this relates to the development of PHP.

TL; DR

PHP does not need to define a class to get its fully qualified name. All the necessary information is available at compile time, so it does not need to be downloaded.

Director Cut

Namespaces such as use are allowed at compile time, i.e. when the file is compiled before its execution. That is why there are strict requirements for their use.

Because of all these requirements, when PHP encounters a class name, it can immediately find out its full name. Seeing this as a file system, the namespace will be a directory for relative locations, and usage will be symbolic links.

The class name is either absolute ("\ Testing \ Test") or relative ("Test"), and if relative it can be a normal name. [more context required]

 namespace Testing { echo Test::class; // \Testing + Test = \Testing\Test } 

Or an alias:

 use Testing\Test as AliasedTest; echo AliasedTest::class; // AliasedTest + use = \Testing\Test 

Without this startup, it won’t work!

::class is just a new disclosure tool that PHP has always known.

This "extended answer" pretty much matches what I got as an error report. The reason for such an obvious copy and paste is that, initially, I created this answer for another community

+5
source share

You can use the get_class function to get the name of the class with a namespace. It will be useful to use it. Here is the code you can try:

 <?php namespace Testing; class Test{ public function abc() { echo "This is the ABC."; } } namespace Testing1; class Test{ public function abc() { echo "This is the ABC."; } } // echo Test::class; // Testing\Test; $test = new Test(); print_r(get_class($test)); // echo "<br>"; // echo UndeclaredClass::class; ?> 
0
source share

All Articles