Method chaining in PHP allows you to call multiple methods on the same object in a single line of code. This is achieved by returning the object itself ($this) from each method, so that the next method can be called on the same instance.
Here’s an example:
Example of Method Chaining in PHP
class Car {
private $speed = 0;
private $gear = 1;
public function setSpeed($speed) {
$this->speed = $speed;
return $this; // Return the current object
}
public function setGear($gear) {
$this->gear = $gear;
return $this; // Return the current object
}
public function display() {
echo "Speed: $this->speed, Gear: $this->gear\n";
return $this; // Return the current object
}
}
// Method chaining example
$car = new Car();
$car->setSpeed(50)->setGear(3)->display();
Explanation:
- Each method (
setSpeed,setGear,display) returns the same object ($this), allowing you to chain method calls in sequence. - This style of code is common in fluent interfaces, making the code more readable and concise.
Use Cases:
- Method chaining is often used in classes like query builders, configuration setters, or even model builders where multiple properties or behaviors are set in sequence.


Leave a Reply