传递给函数的参数必须是可调用的,给定数组

Pad*_*rom 16 php collections laravel

我正在尝试在集合中的每个元素上运行一个方法.它是驻留在同一个类中的对象方法:

protected function doSomething()
{
    $discoveries = $this->findSomething();
    $discoveries->each([$this, 'doSomethingElse']);
}

protected function doSomethingElse($element)
{
    $element->bar();
    // And some more
}
Run Code Online (Sandbox Code Playgroud)

如果我在调用之前Collection::each使用检查is_callable([$this, 'doSomethingElse'])它返回true,那么显然它是可调用的.然而,调用本身会引发异常:

类型错误:参数1传递给Illuminate\Support\Collection :: each()必须是可调用的,给定数组,在第46行中调用--- .php

尝试调用的方法可以在这里找到.

我通过传递一个本身只是调用该函数的闭包来绕过这个,但这肯定是一个更清洁的解决方案,我无法找出它抛出错误的原因.

小智 21

将回调方法的可见性更改为public.

protected function doSomething()
{
    $discoveries = $this->findSomething();
    $discoveries->each([$this, 'doSomethingElse']);
}

public function doSomethingElse($element)
{
    $element->bar();
    // And some more
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*rix 11

从PHP 7.1开始,您可以保护您的功能.现在你可以写:

protected function doSomething()
{
    $discoveries = $this->findSomething();
    $discoveries->each(\Closure::fromCallable([$this, 'doSomethingElse']));
}

protected function doSomethingElse($element)
{
    $element->bar();
    // And some more
}
Run Code Online (Sandbox Code Playgroud)

资源