![](/img/trans.png)
[英]What is the difference between User::class and App\User when setting relations?
[英]Difference between User::class and new User
我正在使用 Laravel 8. 我想知道new User()
和User::class
之間的區別,因為我在使用new User()
時遇到問題。
這是場景,
我有UserServices
class,我正在其中注入UserRepository
class
class UserServices
{
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function findUserByEmail($email){
return $this->userRepository->findUserByEmail($email);
}
}
現在在服務提供商中,當我使用以下方式綁定 UserServices class 時,出現以下錯誤
ArgumentCountError: Too few arguments to function
$this->app->bind(UserServices::class, function($app){
return new UserServices();
});
但是當我使用UserServices::class
時它工作正常
$this->app->bind(UserServices::class);
為什么?
我知道UserServices
class 構造函數需要參數,那么為什么要使用UserServices::class
//工作$this->app->bind(UserServices::class);
//不工作
$this->app->bind(UserServices::class, function($app){
return new UserServices();
});
在第一種情況下,您提供了一個顯式構造函數,該構造函數試圖返回 class 的一個實例,但返回不正確。
在第二種情況下,您將其留給服務容器來確定依賴項並自動注入它們,這會正確地完成。
如果使用的是接口,則需要將接口與服務提供商中的相關class進行綁定。 否則你不需要任何綁定
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.