I have an abstract class that looks like this:
abstract class Transformer { /** * Transform a collection of items * * @param array $items * @param bool $format * @return array */ public function transformCollection(array $items, $format) { return array_map([$this, 'transform'], $items, $format); } /** * Transform a item * * @param array $item * @param bool $format * @return mixed */ public abstract function transform(array $item, $format); }
Then I have the following class that implements it:
class ServiceLogTransformer extends Transformer { public function transform(array $service_log, $format = false) { return [ 'id' => $service_log['id'], 'date' => $service_log['log_date'], 'time' => $service_log['log_time'], 'type' => ($format ? status_label($service_log['log_type']) : $service_log['log_type']), 'entry' => $service_log['log_entry'] ]; } }
When this code runs, I get the error:
How do you pass 2 or more arguments when you call array_map
function within a class? I checked the PHP Documentation and it looks like this is allowed, but it isn't working on my Larave 4.2 project.
Any ideas?
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.
Please always read docs:
http://php.net/manual/en/function.array-map.php
array array_map ( callable $callback , array $array1 [, array $... ] )
and yet you pass bool $format
as argument
"How do you pass 2 or more arguments when you call array_map function within a class?
I would create anonymous function with use()
syntax
public function transformCollection(array $items, $format) { return array_map(function($item) use ($format) { return $this->transform($item, $format); }, $items); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With