Reputation: 3214
I've been reading a lot of documentation for Laravel during last week for the sake of learning what kind of beast it is.
I noticed one thing that whenever somebody references some class he references to it as string, e.g.:
public function user()
{
return $this->belongsTo('App\User');
}
Pay attention to 'App\User'
Taken from here https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations
I wonder why don't they reference it as App\User::class
?
In this case it's easier to type and support the code, because it's easier later to follow the class pressing Ctrl+B. Also refactoring is easier and it's harder to make a mistake because IDE will warn you that class doesn't exist if you make a typo.
I see no reasons to reference class User as 'App\User'
instead of App\User::class
.
Do you see any?
Upvotes: 1
Views: 417
Reputation: 7334
Taking from PHP doc Class Constants:
The special ::class constant are available as of PHP 5.5.0, and allows for fully qualified class name resolution at compile, this is useful for namespaced classes:
This means that using User::class
will at runtime resolve to 'App\User'
according to the example you gave. So the choice is yours.
On a personal note, In order to avoid typographical mistakes with strings I prefer to use the class constant resolution, and also I can easily check the usage from my IDE.
Also I do not have to memorise the namespace of the class I am using.
Apart from these benefit, I do not see any difference unless there is performance difference which obviously does not seem so.
Upvotes: 1
Reputation: 50491
The actual string is used to illustrate that it is the full class name of the related model. You can very easily use Model::class
. The example in the docs is explicit and removes any potential guess work from someone reading that argument.
Upvotes: 0