Artisan72
Artisan72

Reputation: 3600

Laravel5: what's better, class names as strings or Classname::class

In many files in Laravel, maybe in other frameworks, too, you have to specify a class name.

You can either write it with "::class"

App\Models\User::class

or as String:

'App\Models\User'

Well, with the first variant, the class will be loaded right away when it occures. With the second variant I guess it will be loaded when it's going to be used.

Which one is better or recommended? In the Laravel default config files always the "::class" variant is used.

Upvotes: 0

Views: 44

Answers (1)

The Alpha
The Alpha

Reputation: 146191

No, actually App\Models\User::class is the better approach because the ::class returns the fully qualified name of a class. This is more convenient and less error prone. For example:

namespace Some\Name\Space;

use vendor\package\Foo;
use vendor\package\Bar;

class Foo {

    public  function  someMethod()
    {
        // You can't use app('Bar'), You need the FQN
        // So it's possible using the following approach
        $bar = app(Bar::CLASS); // vendor\package\Bar
        $foo = new Foo($bar);

    }
}

This is easily possible to get the class using it's fully qualified name just using Bar::CLASS, so, app(Bar::CLASS) will become app('vendor\package\Bar').

Upvotes: 2

Related Questions