How to implement Method Chaining in PHP ?
Last Updated :
13 Feb, 2024
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
- Each method in the class should return
$this
, allowing the chaining of method calls.
- Call methods sequentially on the same object instance in a single statement.
Example: Implementation of method chaining in PHP.
PHP
<?php
class Calculator {
private $result ;
public function __construct( $initialValue ) {
$this ->result = $initialValue ;
}
public function add( $value ) {
$this ->result += $value ;
return $this ;
}
public function subtract( $value ) {
$this ->result -= $value ;
return $this ;
}
public function multiply( $value ) {
$this ->result *= $value ;
return $this ;
}
public function getResult() {
return $this ->result;
}
}
$calculator = new Calculator(10);
$result = $calculator ->add(5)->subtract(3)->multiply(2)->getResult();
echo $result ;
?>
|
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.
Share your thoughts in the comments
Please Login to comment...