Method Chaining in PHP

Have you ever come across a PHP class that connects methods together in a single line to achieve some goal? (If you haven’t, Guzzle and SwiftMail are a couple of examples.)

//Example from http://guzzlephp.org/
$client = new Client($url);
$request = $client->get('/user')->setAuth('user', 'pass');
$response = $request->send();

jQuery also operates in a similar manner, using the same principle. The technique is called method chaining, and is quite useful in cases where a class has many public methods that could be called upon with each others’ output.

If you wanted, the above example could conceivably be rewritten like this:

$client = new Client($url);
$path = $client->get('/user');
$request = $path->setAuth('user', 'pass');
$response = $request->send();

This works because of the way chainable methods are set up. The secret to making it work is that every method must return the entire object. What you’re doing when you chain Method A with Method B ($object->methodA()->methodB) is calling Method B from the object returned by Method A, which it returned from the object that called it to begin with.

Here’s an example class that permits chaining, since there’s no way that code could be more syntactically awkward than that sentence:

class MyClass {

	function __construct() {
		$this->thing = "a";
	}

	function addB() {
		$this->thing .= "b";
		return $this;
	}

	function addC() {
		$this->thing .= "c";
		return $this;
	}

	function __tostring() {
		return $this->thing;
	}

}

$obj = new MyClass();
echo $obj->addB()->addC(); //outputs "abc"
echo $obj->addB(); //outputs "ab"
echo $obj->addC(); //outputs "ac"
echo $obj; //outputs "a"

When you initialize the object, the constructor sets the thing property to be a. Each one of the methods returns $this, which of course is the entire object. So if you call addB(), it adds b to the string and then returns $this. So you can chain the addC() method, which is basically calling it on the $this that addB() returned.

I hope this helps you understand method chaining. It took me a little while to figure it out, and explaining it clearly is about as easy as reading this probably is. :)

  • http://coursesweb.net CoursesWeb

    vHi,
    To return the class instance in the static method (to chain it), you can use:
    return new self; .
    Here is an example:
    http://coursesweb.net/php-mysq.....ods-php_cs

  • http://catatanbelajar.com/ Catatan Belajar

    Thanks for your explanation simple and easy to understanding about method chaining.

  • Quý Nguyễn Văn

    thank for guide . It is very useful. You can write a guide advance method chaining with variables and implements method from another class.