5ahzmw
Last Updated: October 06, 2016
·
25.47K
· euantor
Irnhmv6

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;
$foo->bar()->output();

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

80
79f39dbd7c90349087908bb13ab8fb55

Cool!

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 ·
86

@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 ·
1286

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 ·
1287
Irnhmv6

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

over 1 year ago ·
5033
C41460d1cfc23cbc64a2639f753d8b70

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

over 1 year ago ·