获取集合中的最后一个元素

7
我正在尝试获取集合中最后一个元素的属性。我尝试了:
end($collection)->getProperty()

and

$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();
}

有什么想法吗?

你确定 $collection 里面有元素吗?在空数组上 end() 会返回 false - aquemini
请提供一些代码以帮助我们更好地协助您。 - Erick
1
$collection->last(); - malcolm
2个回答

16

你遇到的问题是由于集合为空所致。 内部使用last()方法使用end() PHP函数,文档中写道:

返回最后一个元素的值,如果数组为空则返回FALSE。

因此,请按照以下方式更改您的代码:

$property = null

if (!$collection->isEmpty())
{
$property =  $collection->last()->getProperty();
}

希望这有所帮助


0

这个 $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;
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接