I saw a code (I stripped it out for clarity) like this :
require_once __DIR__ . './../vendor/autoload.php'; // composer autoload
if (!class_exists(RtclStore::class)):
final class RtclStore
{
...
}
endif;
I’m wondering how php know what is RtclStore::class before class declaration in the first run? In second run of course the class is defined, but in first run there’s no class so there’s no ::class.
Is this has anything with composer and autoload?
2
Answers
It depends on why and how the code was designed in the first place.
I can think of 2 reasons:
RtclStore
might exists within the scope of autoloading in your composer.If (2) were true, the function class_exists() will trigger the attempt to autoload of
RtclStore
class. Composer will then try to find the class file and include it before doing the actual class exists check.In both case,
RtclStore
might or might not exists before the condition check. And it makes sense to only declareRtclStore
after check.RtclStore::class
is just a simple string. From the PHP perspective, it’s plain text.Demo
One benefit is that IDEs and linters are able to identify them as class usages. Another one is that you get a fully-qualified name according to current namespace:
Demo
So it’s basically a smart namespace-aware text generator 🙂
Aside that, class_exists() just receives a class name as string and triggers autoloading or not depending on the value for its second argument:
You could just pass the generated string and everything would work the same way: