返回每个对象或一个 arrayCollection 之间的区别
Difference between returning each object or one arrayCollection
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;
});
将 return 所有 个匹配的项目,或者在未找到任何内容时返回一个空的 ArrayCollection。
同时
foreach ($this->invoiceItems as $invoice) {
if ($invoice->getType() == $type) {
return $invoice;
}
}
return null;
只会 return 匹配 $invoice->getType() == $type
的数组的第一项 或如果根本不存在则为 null。
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;
});
将 return 所有 个匹配的项目,或者在未找到任何内容时返回一个空的 ArrayCollection。
同时
foreach ($this->invoiceItems as $invoice) {
if ($invoice->getType() == $type) {
return $invoice;
}
}
return null;
只会 return 匹配 $invoice->getType() == $type
的数组的第一项 或如果根本不存在则为 null。