[英]Get last element in Collection
我正在嘗試獲取集合中最后一個元素的屬性。 我試過了
end($collection)->getProperty()
和
$collection->last()->getProperty()
沒有辦法
(告訴我,我正在嘗試在布爾值上使用getProperty()
)。
/**
* Get legs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getLegs()
{
return $this->aLegs;
}
public function getLastlegdate()
{
$legs = $this->aLegs;
return $legs->last()->getStartDate();
}
知道為什么嗎?
您有問題是由於集合為空。 在內部, last()
方法使用doc中的end()
php函數:
返回空數組的最后一個元素的值或FALSE。
因此,如下更改代碼:
$property = null
if (!$collection->isEmpty())
{
$property = $collection->last()->getProperty();
}
希望這個幫助
$collection->last()->getProperty()
違反了Demeter的定律。 該職能應負單一責任。 嘗試這個。
/**
* @return Leg|null
*/
public function getLastLeg(): ?Leg
{
$lastLeg = null;
if (!$this->aLegs->isEmpty()) {
$lastLeg = $this->aLegs->last();
}
return $lastLeg;
}
/**
* @return \DateTime|null
*/
public function getLastLegDate(): ?\DateTime
{
$lastLegDate = null;
$lastLeg = $this->getLastLeg();
if ($lastLeg instanceOf Leg) {
$lastLeg->getStartDate();
}
return $lastLegDate;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.