Reputation: 125
I am a beginner in Laravel and while learning about "namespace" and "use" statements, I found that, for example, in Controllers, when we first write "use" statements it should be repeated inside of the function.
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
Why is this working so? Why is not it enough to write "use" statements once without repeating in a function? And also, if I will create another Controller with the same namespace, should I write the same "use" statements there as well?
Upvotes: 0
Views: 776
Reputation: 522042
There are two different use
in PHP:
The use
at the top of the file aliases namespaced names into shorter local ones. Literally their only use is so you can write DispatchesJobs
inside this one file instead of having to always use the fully qualified name \Illuminate\Foundation\Bus\DispatchesJobs
.
use
inside a class
applies that trait to the class.
In this case you could omit the first use
to alias the trait, and apply it using its fully qualified name:
namespace App\Http\Controllers;
class Controller extends \Illuminate\Routing\Controller {
use \Illuminate\Foundation\Bus\DispatchesJobs;
...
}
This does exactly the same thing, but is obviously rather verbose. Establishing a few aliases at the top of the file allows your following code to be terser.
Upvotes: 8
Reputation: 34914
Using keyword use
outside class is just importing specific part called trait
.
And using keyword use
inside class is actually inheriting or implements to use that trait
Upvotes: 1