Method Chaining in PHP allows calling multiple object methods in a single statement. Each method returns the same object using $this, enabling fluent and readable code.
$thisWhen a method returns the current object instance, another method can be immediately called on the returned object. This creates a chain of method calls on the same object.
// PHP class demonstrating method chaining
name = $name;
return $this;
}
public function setEmail($email) {
$this->email = $email;
return $this;
}
public function save() {
echo "Saving user: {$this->name}, {$this->email}";
return $this;
}
}
$user = new User();
$user->setName("Alice")->setEmail("alice@example.com")->save();
?>
The object instance returned by each method allows the next method to execute immediately. All operations happen on the same $user object.
// JavaScript-style chaining logic simulation
const user = {
name: "",
email: "",
setName(n) {
this.name = n;
return this;
},
setEmail(e) {
this.email = e;
return this;
},
show() {
console.log(this.name, this.email);
return this;
}
};
user.setName("Bob").setEmail("bob@example.com").show();
$this consistentlyProduct class with chained setters
// Multi-line formatted method chain
$user->setName("Bob")
->setEmail("bob@example.com")
->save();