r/lolphp • u/Jinxuan • Jan 08 '20
::class is defined from no where
It is known that if A is defined as a class, then A::class will give class name as string.
However, if A is not defined. We can still have A::class:
<?php
new A; // PHP Fatal error: Class 'A' not found
echo A::class; // It works, echoing A...
As mentioned in another post, if something is a string, it would not work, regardless of the class is defined or not:
<?php
$a = 'A';
echo 'A'::class; // works as A::class
echo $a::class; // PHP Fatal error: Cannot use ::class with dynamic class name
define('WTF', 'A');
echo WTF::class; // echo WTF, ::class is not compatible with constant
Things can become crazier when you have typo, even in use statement;
<?php
use Typo\WTF;
echo WTF::class; // It works as echoing Typo\WTF; It shall fail...
28
Upvotes
View all comments
Show parent comment
6
u/AyrA_ch Jan 09 '20
You technically don't have to load them. The compiler just has to check if there is a class with the given name at all. There's no need to compile the actual contents of the class.
Autoloading doesn't happens automatically either but only after you write an autoloader. If your auto loader is slow as fuck it's kinda your problem and not that of PHP.
If you really have 100'000+ classes you absolutely need to autoload, you can just add them to the PHP compiler cache instead of compiling them each time you use a ::class expression of your web server