Laravel 通用集合

Laravel Generic Collections

我的 Java 经验告诉我,我可以像这样创建通用集合:

Collection<E> collection = new Collection<E>();

我想知道这在 Laravel(至少 5.2+)中是否可行?我已经使用 Laravel 将近 3 年了,现在只是想知道这个问题。

例如,我在创建一个 Laravel 模型转换器函数时想到了这一点,如下所示:

当前Laravel函数:

public function transformMultiple(Collection $models){

        $collection = collect();

        foreach($models as $m){
            $collection->push($this->transform($m));
        }

        return $collection;
    }

使用泛型的假设函数:

public function transformMultiple(Collection<Foo> $models){

        $collection = collect();

        foreach($models as $m){
            $collection->push($this->transform($m));
        }

        return $collection;
    }

感谢@AlexSlipKnot 的评论,我相信 PHP 目前不支持泛型;然而,it may support it in the future. His other link in the comments (a Whosebug answer to a similar question) also provides in-depth guidelines to custom implementations; however, if one is to develop their own custom implementation, they need to beware of applicable O.O Design Principles.