Search code examples
phplaravelcoding-style

Laravel - referencing the class


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?


Solution

  • 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.