Rowayda Khayri
Rowayda Khayri

Reputation: 489

Using use statements inside and outside a PHP class to import traits

Why should we use use statement to import a trait outside the class and then use it again inside the class ??!

Example (in Laravel User model) :

use Illuminate\Database\Eloquent\SoftDeletes;


class User extends Authenticatable
{

    use SoftDeletes;
.
.
.
.
.

}

Why are traits treated in different way other than other classes where we just import namespace once outside the class and can use it directly ?!

Upvotes: 0

Views: 1655

Answers (3)

online Thomas
online Thomas

Reputation: 9381

Because the first use indicates which class to use that is already required by the autoloader. This helps prevent collision of classes with the same name.

E.g.

// same name but avoid collision by an alias
use App\Models\Request as RequestModel;
use Request;

The second use is bound to the Trait and indicates that it should be used in this class. You can (bad practice) have multiple classes defined in 1 file, that is why you need to show that you want to use the Trait on that specific class.

class A {
    use SomeTrait;
}

class B {
   /// not using Trait
}

edit: Maybe it's good to know there are 3 uses of the use keyword in PHP, all having a different meaning.

  1. use App\Models\Product;
    

    Means: Use this Full Qualified Name when I type Product in the class(es) below.

  2. class User
    {
        use SoftDeletes;
    

    Means: Load the Trait SoftDeletes in this Class (inject some functions).

  3. collect([])->map(function ($id) use ($product) {
     // function body
    });
    

    Means: use the variable $product inside the new anonymous function which has it's own scope. Without it you couldn't access the $product variable inside the function's body.

Upvotes: 1

Bikash
Bikash

Reputation: 1938

Use of outside of class to include actual class using the namespace. Thus it is just included but not used in that class just yet.

If you really need to use that class inside the class then you need to use this inside the class.

You can omit the use outside the class by following way.

use Illuminate\Database\Eloquent\SoftDeletes ;

inside the class directly.

Upvotes: 2

kip
kip

Reputation: 1140

use keyword has different meaning in each context.

  • Inside a class determinate the trait(s) that class use See.
  • In closures use is used to determine the vars to import inside the scope See.
  • Out of all, use import the namespace of a class to mapper a classname with that, is possible too set an alias with combination of use and as See.

Upvotes: 2

Related Questions