skip to Main Content

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


  1. It depends on why and how the code was designed in the first place.

    I can think of 2 reasons:

    1. The file you refers to would be included multiple times in the program. In that case, do the class_exists() check will prevent PHP error in redeclaring class.
    2. A version of 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 declare RtclStore after check.

    Login or Signup to reply.
  2. RtclStore::class is just a simple string. From the PHP perspective, it’s plain text.

    var_dump(ANYTHINGYOUWANT::class);
    
    string(17) "ANYTHINGYOUWANT"
    

    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:

    namespace OneTwoThree;
    
    var_dump(FOOBAR::class);
    
    string(21) "OneTwoThreeFOOBAR"
    

    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:

     class_exists(string $class, bool $autoload = true): bool
    

    You could just pass the generated string and everything would work the same way:

    if (!class_exists('RtclStore')) // Or whatever the file namespace is
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search