The argument passed to the function must be callable, the array is given

I am trying to run a method for each item within a collection. This is an object method located in the same class:

protected function doSomething() { $discoveries = $this->findSomething(); $discoveries->each([$this, 'doSomethingElse']); } protected function doSomethingElse($element) { $element->bar(); // And some more } 

If I precede a call to Collection::each with the is_callable([$this, 'doSomethingElse']) tag is_callable([$this, 'doSomethingElse']) , it returns true, so apparently it could be called. However, the call itself throws an exception:

Type error: argument 1 passed to the illustration \ Support \ Collection :: each () must be called, the array is specified, called in ---. php on line 46

The method to call can be found here .

I will get around this by simply passing a closure that itself simply calls this function, but it is certainly a much cleaner solution, and I cannot understand why it throws an error.

+16
collections php laravel
source share
3 answers

Change the visibility of the callback method for sharing.

 protected function doSomething() { $discoveries = $this->findSomething(); $discoveries->each([$this, 'doSomethingElse']); } public function doSomethingElse($element) { $element->bar(); // And some more } 
+21
source share

Starting with PHP 7.1, you can leave your function protected. Now you can write:

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

A source

+11
source share

PHP> = 5.4

I could not reproduce your error, but I assume that in the callback array you should use $discoveries instead of $this , for example:

 $discoveries->each([$discoveries, 'doSomethingElse']); 

Despite the fact that $discoveries and $this have the same class and, therefore, can access other protected and private methods, the type hint function may not check that the object in the callback array is the same class as the current one class. However, the is_callable() method checks this, which may explain why it returns true when you call it from each() method.

PHP <5.4

There is no type called callable , so when you use it as a type hint, it refers to a class called callable . See this answer.

-one
source share

All Articles