Create total as an instance variance
protected $total;
then change your function to this
public function total()
{
$this->total = $this->subtotal();
foreach ($this->lineItems as $l) {
$this->total += $l->amount;
}
return $this;
}
then create the formated function
public function formated()
{
return number_format($this->total, 2)
}
now you can chain the function like
$order->total()->formated()
** Updated **
you can return both total and subtotal in formated function
public function formated()
{
return [
"total" => number_format($this->total, 2),
"subtotal" => number_format($this->subtotal, 2)
];
}
** or **
you can use one instance variable for both total and or subtotal. let name this varibles myTotals
protected $myTotals;
public function total()
{
$this->myTotals = $this->subtotal();
foreach ($this->lineItems as $l) {
$this->myTotals += $l->amount;
}
return $this;
}
public function subTotal()
{
$this->myTotals = $this->subtotal();
foreach ($this->lineItems as $l) {
$this->myTotals += $l->amount;
}
return $this;
}
public function formated()
{
return number_format($this->myTotals, 2)
}
so in this case you can call
$order->total()->formated() // and this will return the total
$order->subTotal()->formated() // and this will return the subtotal