Home > Software design >  Difference between User::class and new User
Difference between User::class and new User

Time:03-07

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();
});

CodePudding user response:

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.

CodePudding user response:

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

  • Related