Open In App

How to implement Method Chaining in PHP ?

Method Chaining is a technique in object-oriented programming where multiple methods are invoked sequentially on the same object instance in a single statement. In PHP, method chaining can be achieved by returning the object itself ($this) from each method call, allowing subsequent methods to be called on the same object.

Approach

Example: Implementation of method chaining in PHP.






<?php
class Calculator {
    private $result;
 
    public function __construct($initialValue) {
        $this->result = $initialValue;
    }
 
    public function add($value) {
        $this->result += $value;
        return $this; // Return $this for method chaining
    }
 
    public function subtract($value) {
        $this->result -= $value;
        return $this; // Return $this for method chaining
    }
 
    public function multiply($value) {
        $this->result *= $value;
        return $this; // Return $this for method chaining
    }
 
    public function getResult() {
        return $this->result;
    }
}
 
// Example usage of method chaining
$calculator = new Calculator(10);
$result = $calculator->add(5)->subtract(3)->multiply(2)->getResult();
echo $result; // Output: 24
 
?>

Output
24




Explanation



This code demonstrates how to implement method chaining in PHP using the Calculator class as an example. Each method (add(), subtract(), multiply()) returns$this, allowing them to be chained together. Finally, getResult() is called to obtain the final result.


Article Tags :