如何在PHP中为匿名函数赋值参数

时间:2018-04-11 04:23:06

标签: php laravel lumen

read变量的值如何来自$item

$products

2 个答案:

答案 0 :(得分:0)

如果您深入了解laravel框架,$products的类型为Illuminate\Database\Eloquent\Collection。它实现了map方法,underlying implementation是:

public function map(callable $callback)
{
    $result = parent::map($callback);
    return $result->contains(function ($item) {
        return ! $item instanceof Model;
    }) ? $result->toBase() : $result;
}

Illuminate\Database\Eloquent\Collection的父类是Illuminate\Support\Collection,而underlying implementation是:

public function map(callable $callback)
{
    $keys = array_keys($this->items);
    $items = array_map($callback, $this->items, $keys);
    return new static(array_combine($keys, $items));
}

它使用array_map方法,它会将回调函数应用于每个值。

array array_map ( callable $callback , array $array1 [, array $... ] )

答案 1 :(得分:0)

一个简单的例子,向您展示如何实现它  https://implode.io/Ce1azD

class Products
{
    protected $items = [];

    public function __construct($items)
    {
        $this->items = $items;
    }

    public function map(callable $callback)
    {
        return array_map($callback, $this->items);
    }
}

$products = new Products([1, 2, 3, 4]);

return $products->map(function ($item) {
    return $item * 2;
});