加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 返回每个对象或一个arrayCollection之间的区别

发布时间:2020-12-13 21:33:17 所属栏目:PHP教程 来源:网络整理
导读:public function getInvoiceItemsByType($type){ return $this-invoiceItems-filter(function ($invoice) use ($type) { /** @var InvoiceItem $invoice */ return $invoice-getType() == $type; } );}public function getInvoiceItemsByType($type) { forea
public function getInvoiceItemsByType($type)
{
    return $this->invoiceItems->filter(function ($invoice) use ($type) {
        /** @var InvoiceItem $invoice */
        return $invoice->getType() == $type;
    }
    );
}

public function getInvoiceItemsByType($type) {
    foreach ($this->invoiceItems as $invoice) {
        if ($invoice->getType() == $type) {
            return $invoice;
        }
    }
    return null;
}

这两个功能有区别吗?有人告诉我有一个,但我无法找到它是什么,以及一个函数而不是另一个函数将如何影响我的代码

解决方法

不同之处在于

return $this->invoiceItems->filter(function ($invoice) use ($type) {
    /** @var InvoiceItem $invoice */
    return $invoice->getType() == $type;
});

将返回所有匹配的项或者在找不到任何内容时返回空的ArrayCollection.

foreach ($this->invoiceItems as $invoice) {
    if ($invoice->getType() == $type) {
        return $invoice;
    }
}
return null;

只会返回匹配$invoice-> getType()== $type的数组的第一项,如果它根本不存在则返回null.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读