code_locked
code_locked

Reputation: 125

"use" statements in php file

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

Answers (2)

deceze
deceze

Reputation: 522042

There are two different use in PHP:

  1. To alias namespaced names,
  2. to apply traits to classes.

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

Niklesh Raut
Niklesh Raut

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

Related Questions