Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I chain methods in PHP?
Method chaining in PHP allows you to call multiple methods on an object in a single line by returning $this from each method. This creates a fluent interface that makes code more readable and concise.
How Method Chaining Works
To enable method chaining, each method must return the current object instance using return $this. This allows the next method to be called on the returned object ?
<?php
class sample_class {
private $str;
function __construct() {
$this->str = "";
}
function addA() {
$this->str .= "am";
return $this;
}
function addB() {
$this->str .= "_bn";
return $this;
}
function getStr() {
return $this->str;
}
}
$new_object = new sample_class();
echo $new_object->addA()->addB()->getStr();
?>
am_bn
Practical Example
Here's a more practical example with a QueryBuilder class ?
<?php
class QueryBuilder {
private $query = "";
public function select($fields) {
$this->query = "SELECT " . $fields;
return $this;
}
public function from($table) {
$this->query .= " FROM " . $table;
return $this;
}
public function where($condition) {
$this->query .= " WHERE " . $condition;
return $this;
}
public function getQuery() {
return $this->query;
}
}
$builder = new QueryBuilder();
$sql = $builder->select("name, email")
->from("users")
->where("age > 18")
->getQuery();
echo $sql;
?>
SELECT name, email FROM users WHERE age > 18
Key Points
- Always return
$thisfrom methods you want to chain - The last method in the chain can return any value (not necessarily
$this) - Method chaining improves code readability and reduces variable assignments
- Commonly used in frameworks like Laravel for query building and form handling
Conclusion
Method chaining in PHP creates fluent interfaces by returning $this from each method. This pattern makes code more readable and allows for elegant, chainable API designs commonly seen in modern PHP frameworks.
Advertisements
