← Back to Chapters

PHP OOP Method Chaining

? PHP OOP Method Chaining

? Quick Overview

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.

? Key Concepts

  • Each method must return $this
  • Works only with objects
  • Improves readability and fluency
  • Common in frameworks and query builders

? Syntax & Theory

When 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.

? Code Example

? View Code Example
// 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();
?>

? Live Output / Explanation

The object instance returned by each method allows the next method to execute immediately. All operations happen on the same $user object.

? Interactive Example

? View Code Example
// 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();

?️ Use Cases

  • ORM and database query builders
  • Configuration builders
  • Fluent APIs
  • Object setup pipelines

✅ Tips & Best Practices

  • Return $this consistently
  • Keep chains readable
  • Break long chains into lines
  • Use chaining where it adds clarity

? Try It Yourself

  • Create a Product class with chained setters
  • Build a simple query builder
  • Experiment with inheritance and chaining
? View Code Example
// Multi-line formatted method chain
$user->setName("Bob")
->setEmail("bob@example.com")
->save();