Method Chaining In PHP – Fluent Interface

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, January 23, 2009

Follow me on Twitter as @mattiasgeniar

The technical definition of “Fluent Interface”, as defined by Wikipedia, is: “An object oriented construct that defines a behavior capable of relaying the instruction context of a subsequent call.". It’s just as sexy as it sounds.

In short: any Object Oriented language allows you to call upon a new method, directly followed by another one and still updating the same parent object.

Code explains this easier. The following examples creates a one-armed, one-legged and one-headed person.

class Person {
	public function addLeg() {
		// Adds a leg
	}

	public function addArm() {
		// Adds an arm
	}

	public function addHead() {
		// Adds a head
	}

	// .... and the list goes on
}

$person = new Person();
$person->addLeg();
$person->addArm();
$person->addHead();

After creating an instance of the object Person, we call upon every method once to add a certain body part.

If we slightly rewrite the class, by returning the object itself upon every method call, we can also write those method calls like this.

class Person {
	public function addLeg() {
		// Adds a leg

		return $this;
	}

	public function addArm() {
		// Adds an arm

		return $this;
	}

	public function addHead() {
		// Adds a head

		return $this;
	}

	// .... and the list goes on
}

$person = new Person();
$person->addLeg()->addArm()->addHead();

While this may, or may not, help in readability – the option to use Fluent Interfaces exist in PHP5 (and JavaScript as well, in the same way). It’ll depend on the situation whether or not this is useful. I can see this creating very chaotic code, and it’s a serious PITA to handle errors or exceptions this way.



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.