Method Chaining or Fluent Interface in PHP
Method chaining, also known as a fluent interface, is a programming technique that allows you to call multiple methods on an object in a single statement. This can greatly improve code readability and maintainability.
To implement method chaining in PHP, you simply need to ensure that all your mutator methods (setters) return the original object.
Consider the example below:
class fakeString { private $str; function __construct() { $this->str = ""; } function addA() { $this->str .= "a"; return $this; } function addB() { $this->str .= "b"; return $this; } function getStr() { return $this->str; } } $a = new fakeString(); echo $a->addA()->addB()->getStr();
This code outputs "ab". The addA and addB methods return the fakeString object, allowing you to chain multiple method calls together without the need for temporary variables or interim object references.
The above is the detailed content of How Does Method Chaining (Fluent Interface) Work in PHP?. For more information, please follow other related articles on the PHP Chinese website!