Reputation: 489
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
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.
use App\Models\Product;
Means: Use this Full Qualified Name when I type Product in the class(es) below.
class User
{
use SoftDeletes;
Means: Load the Trait
SoftDeletes in this Class (inject some functions).
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
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
Reputation: 1140
use
keyword has different meaning in each context.
use
is used to determine the vars to import inside the scope See.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