阅读(2141) (8)

Laravel 8 扩展集合

2021-06-30 17:55:41 更新

集合都是「可宏扩展」(macroable) 的,它允许你在执行时将其它方法添加到 Collection 类。例如,通过下面的代码在 Collection 类中添加一个 toUpper 方法:

use IlluminateSupportCollection;
use IlluminateSupportStr;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return Str::upper($value);
    });
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

// ['FIRST', 'SECOND'] 

通常,你应该在服务提供者内声明集合宏。