Last Updated: January 23, 2019
· euantor

Chaining methods in PHP

All the cool kids are method chaining these days. For those who don't know what method chaining is, it looks a little like this:

$foo = new Foo;

Looks much nicer than two separate calls, yes? Here's an implementation example from a simple Gravatar class of mine:

public function SetEmail($email = '')
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $this->email = md5(strtolower(trim($email)));

    return $this;

It's simple - all we have to do is ensure we return $this at the end of our methods that we wish to be chain-able.

5 Responses
Add your response



I think it worth noting that for JavaScript it works the same way:

(dahm it, indentation don't works in comments)

function setEmail(email)
     return this;

Aslo for CoffeeScript:

setEmail = (email) ->
over 1 year ago ·

@hnordt I do believe we can write html freely anywhere in this site. I dunno what tags are allowed, let's see: <strong>strong</strong>, code</code>, <br/> br, paragraph with inline style...</p>, <div>div</div>.... Well, it seems comments are put inside P tags, yet div is allowed, which breaks the presentation a bit. I'm guessing it's an issue and not a feature... and I think I just broke pretty much everything. </p>

over 1 year ago ·

it may be worth noting that this is also known as "fluent interface".

i usually add this as a comment on the '@return' phpdoc annotation

over 1 year ago ·

@etienne Good point, I hadn't thought about mentioning the real name.

over 1 year ago ·

Yes, this is known feature in php. It's called "fluent".

over 1 year ago ·