How to include php aliases in files
I can write this to a file:
use Carbon\Carbon as Carbon;
I tried to create a file 'aliases.php':
use Carbon\Carbon as Carbon;
which I then link like this:
require __DIR__.'/../bootstrap/aliases.php';
printf("Right now is %s", Carbon::now()->toDateTimeString());
but it gives me an error: "Fatal error: class 'Carbon' not found"
So how can I "include" one file with all the predefined aliases?
source to share
First of all, the reason your aliases.php file is not working is because the use statements are only visible inside the file in which they were declared. in other words, they work in your aliases.php file , but not in files that include / require aliases.php.
From PHP documentation Using Namespaces: Aliasing / Importing :
Note:
The import rules are file-based, which means that included files do NOT inherit the import rules of the parent file.
Second, because of the way the namespace works in PHP, it fails to accomplish what you are trying to do . When PHP sees the name of a class, it always tries to find the class in the current namespace and there is no way to change it. Therefore, if you call Carbon in any namespaced code, it will be interpreted as Current \ Namespace \ Carbon , and if you call it from the global namespace, it will be interpreted as \ Carbon .
The only thing that comes to my mind that can do something like this is to declare a class in the global namespace that will extend the class you are trying to use, and then use those classes instead. For carbon, this would be:
<?php
use Carbon\Carbon as BaseCarbon;
class Carbon extends BaseCarbon {}
Then in your code, you can access it:
\Carbon::now();
Keep in mind that you need the \ prefixed class name so that it will always be accepted from the global namespace, unless the code you are executing is already in the global namespace.
source to share