phpnamespacesaliases

how to include php aliases across files


I can write this in a file:

use Carbon\Carbon as Carbon;

I have tried to create a file 'aliases.php':

use Carbon\Carbon as Carbon;

which I then reference like so:

require __DIR__.'/../bootstrap/aliases.php';

printf("Right now is %s", Carbon::now()->toDateTimeString());

but that gives me the error: "Fatal error: Class 'Carbon' not found"

So how can I 'include' one file with all the pre-defined aliases?


Solution

  • First of all, the reason why your aliases.php file doesn't work is because use statements are visible only within the file they're declared in. In other words they work in your aliases.php file, but not in files that include/require aliases.php.

    From the PHP documentation Using namespaces: Aliasing/Importing:

    Note:

    Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

    Secondly, due to how namespacing works in PHP, it's not possible to do what you are trying to do. When PHP sees a class name, it always tries to find the class in the current namespace and there is no way to change that. Therefore, if you call Carbon in any namespaced code, it will be interpreted as Current\Namespace\Carbon, and if you call it from global namespace, it will be interpreted as \Carbon.

    The only thing that comes to my mind that could do something similar is to declare a class in the global namespace that would extend the class you're trying to use and then use those classes instead. For carbon it would be:

    <?php
    use Carbon\Carbon as BaseCarbon;
    
    class Carbon extends BaseCarbon {}
    

    Then in your code you could access it by:

    \Carbon::now();
    

    Keep in mind that you'll need to prefix the classname with \ so that it's always taken from the global namespace, unless the code you're executing is in global namespace already.