Method chaining technique gives us ability to call several methods with only one PHP expression (in one go)
class Bill {
public $dinner = 20;
public $dessert = 5;
public $drink = 3;
public $bill = 0;
public function dinner($count) {
$this->bill += $count * $this->dinner;
return $this;
}
public function dessert($count) {
$this->bill += $count * $this->dessert;
return $this;
}
public function drink($count) {
$this->bill += $count * $this->drink;
return $this;
}
}
$bill = new Bill;
We can call several methods one by one and print the
$bill
:
$bill->dinner(3);
$bill->dessert(2);
$bill->drink(1);
echo $bill->bill;
Or we can combine the above 4 expressions using method chaining. The result will be the same:
echo $bill->dinner(3)->dessert(2)->drink(1)->bill;