Php Laravel类型错误:参数太少?
我得到一个错误: 类型错误:参数太少 我想拉威尔会做一些魔术来防止争论没有完全通过 例如: 在控制器中,我有:Php Laravel类型错误:参数太少?,php,laravel,laravel-5,laravel-5.4,Php,Laravel,Laravel 5,Laravel 5.4,我得到一个错误: 类型错误:参数太少 我想拉威尔会做一些魔术来防止争论没有完全通过 例如: 在控制器中,我有: public function create(CreateRequest $request) { return $this->todoService->createList($request); } 在todoService类中: use App\Plan class todoService { public function createLis
public function create(CreateRequest $request)
{
return $this->todoService->createList($request);
}
在todoService
类中:
use App\Plan
class todoService {
public function createList($request, Plan $plan)
{
//
}
}
正如您所看到的,我没有传递
Plan
class对象。我必须绑定还是做些什么?Laravel无法在这一级别上发挥任何作用,因为您的编码错误只是一个PHP语法错误。您正在指示第二个参数的类型为Plan
,这使得它隐式地成为必需的。Laravel无法“修补”这样的简单函数调用
您的困惑可能在于,根据您的路由,Laravel可以将正确的
Plan
参数注入create
controller方法,从而允许您将其转发到服务中。如果您自己调用createList(),那么您需要自己传递这两个参数。你可以用Plan绑定一些东西,但如果你调用的不是Laravel,那么你将负责传递函数参数
这种类型的暗示仅在Laravel调用该函数时有效。所以你需要通过Laravel调用这些函数
如果您试图自动注入类的构造函数,只需执行以下操作:
$service = $this->app->make('App\Plan\todoservice');
或
或
但这只适用于构造函数。请注意,您还可以提供参数作为make()
或resolve()
函数的下一个参数
事实上,不同的方法也可以这样调用
您可以简单地执行以下操作:
$service = App::make('App\Plan\todoservice');
$container->call([$service, 'createList'], ['request' => $request] );
这里,
$container
是illighted\Contracts\container\container
的对象,只有当类依赖于接口时,才需要绑定类。如果指定特定的类,反射将为您完成这项工作
唯一可行的方法是设置第二个参数的默认值。在任何其他情况下,都会引发语法异常
use App\Plan
class todoService
{
public function createList($request, Plan $plan = null)
{
//
}
}
public function create(CreateRequest $request)
{
return $this->todoService->createList($request);
}
它会起作用,但这有意义吗
/**
* Create a new personal access token for the user.
*
* @param string $name
* @param array $scopes
* @return \Laravel\Passport\PersonalAccessTokenResult
*/
public function createToken($name, array $scopes = [])
{
return Container::getInstance()->make(PersonalAccessTokenFactory::class)->make(
$this->getKey(), $name, $scopes
);
}
/**
* Set the current access token for the user.
*
* @param \Laravel\Passport\Token $accessToken
* @return $this
use App\Plan
class todoService
{
public function createList($request, Plan $plan = null)
{
//
}
}
public function create(CreateRequest $request)
{
return $this->todoService->createList($request);
}
/**
* Create a new personal access token for the user.
*
* @param string $name
* @param array $scopes
* @return \Laravel\Passport\PersonalAccessTokenResult
*/
public function createToken($name, array $scopes = [])
{
return Container::getInstance()->make(PersonalAccessTokenFactory::class)->make(
$this->getKey(), $name, $scopes
);
}
/**
* Set the current access token for the user.
*
* @param \Laravel\Passport\Token $accessToken
* @return $this