Search code examples
phpimportphp-7.3magic-constants

Can magic constants be imported in PHP


I cannot find any hint about the fact I cannot import any magic constant.

Trying to like ...

<?php declare( strict_types = 1 );
namespace CodeKandis\MyVendor;

use function dirname;
use const __DIR__;

require_once dirname( __DIR__ ) . '/vendor/autoload.php';

... leads to

Parse error: syntax error, unexpected '__DIR__' (T_DIR), expecting identifier (T_STRING) or \\ (T_NS_SEPARATOR) in /public/index.php on line 5

This question is important while PHPStorm tends to auto import magic constants. And if it's not possible this needs to be reported and fixed.


Edit (2019-07-25)

After I opened an issue this will be fixed in PHPStorm 2019.3.


Solution

  • In PHP only OOP stuff (classes, interfaces, exceptions, errors...) must be fully named-qualified. If you do not specify full name or do not import class into another namespace, PHP will not fallback to global namespace to look for it.

    You can also use fully-specified functions or constants. Functions can belong to a namespace, and in fact all core functions belong to global namespace i.e. \. PHP will first look for the function in the current namespace and it will fall back to global functions or constants if a namespaced function or constant does not exist. You can perform micro-optimization if you specify the global namespace explicitly, because PHP will look in the global namespace directly.

    namespace A {
        function phpinfo(){
            echo 'I am bogus';
        }
        phpinfo(); // vs. \phpinfo()
    }
    

    Magic constants are not really constants at all. They change value based on the context. They are more like magic variables. The following code is invalid, because these constants do not belong to any namespace, not even the global one.

    namespace A {
        echo \__LINE__;
    }
    

    At compile time PHP will substitute them with the actual values. They can't be imported either for exactly the same reason, they are not defined anywhere, they are simply an instruction for the compiler.

    There are also other things which can't be imported or namespaced, see: List of Keywords.

    You cannot use any of the following words as constants, class names, function or method names.

    namespace A {
        \echo 'hi'; // <-- this line is invalid code
        \die(1); // neither is this, even if it looks and behaves like a function
    }
    

    Some people confusingly put parentheses after echo or print, treating them like functions, but in reality they are not. The ones listed with parentheses behave like functions accepting parameters, but you can't import them either.