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

Get last element in Collection

我正在尝试获取集合中最后一个元素的 属性。我试过了

end($collection)->getProperty()

$collection->last()->getProperty()

none 有效

(告诉我我正在尝试对布尔值使用 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() 方法使用 end() php 函数 from the doc:

Returns the value of the last element or FALSE for empty array.

所以按如下方式更改您的代码:

$property = null

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

希望对您有所帮助

$collection->last()->getProperty()违反了得墨忒耳的法则。该功能应具有单一职责。试试这个。

/**
 * @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;
 }