Difference between User::class and new User

123 Views Asked by At

I am using Laravel 8. I want to know the difference between new User() and User::class because I am having trouble while using new User().

Here is the scenario,

I have UserServices class in which I am injecting UserRepository class

class UserServices
{
    private $userRepository;
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function findUserByEmail($email){
        return $this->userRepository->findUserByEmail($email);
    }

}

Now in service provider when I bind the UserServices class using following way I am getting following error

ArgumentCountError: Too few arguments to function

$this->app->bind(UserServices::class, function($app){
    return new UserServices();
});

But when I use UserServices::class then it works fine

$this->app->bind(UserServices::class);

Why?

I know that UserServices class constructor is expecting parameter then why working with UserServices::class

//Working $this->app->bind(UserServices::class);

//Not Working

$this->app->bind(UserServices::class, function($app){
    return new UserServices();
});
2

There are 2 best solutions below

0
On BEST ANSWER

In the first case, you're providing an explicit constructor which attempts to return an instance of the class, but does it incorrectly.

In the second case, you're leaving it up to the service container to determine dependencies and inject them automatically, which does it correctly.

0
On

If you are using an interface then you need to bind the interface with the related class in the service provider. Otherwise you don't need any binding