Search code examples
phpincluderequiremagic-constants

Can anyone tell what is the relation of include and require with magic constants in php?


I am learning to include and require constructs on php.net and found the line An exception to this rule are magic constants which are evaluated by the parser before the include occurs. on 7 paragraph of that page but didn't understand that what is the relation of magic constants with include and require in php.

Can anyone tell in simple and easy words ?

It is fine to negative mark my question but please must answer, i want to know and learn, negative marking doesn't matter.


Solution

  • Before your code is parsed, the parser resolves all include and require so it can parse it all as if it was one script. However, before it resolves those, any magic constants, like __DIR__ will be resolved.

    An example:

    Imagine that you have two files:

    file1.php

    <?php
    require __DIR__ . '/file2.php';
    
    echo 'Hello ' . $a;
    

    file2.php

    <?php
    $a = 'World';
    

    As you see, there is a magic constant: __DIR__ in there. That constant will return the absolute path to the file I wrote it in. So the parsed resolves that first:

    <?php
    require '/the-current-folder/file2.php';
    

    Then it actually includes any include and require so it gets:

    <?php
    $a = 'World';
    
    echo 'Hello ' . $a;
    

    Then it parses the script:

    Hello World