Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

chaining methods in PHP

I rarely find myself needing to chain methods in PHP – but its not an altogether bad idea. The only caveat that is necessary is that your code must be written in such a way that a method can fail, but other methods can still continue. For example, you couldn’t have one method return false… that would break the chain. You also couldn’t have a method depending on the actions of the previous method to be successful if it is allowed to legitimately fail. There is no intermediate step to check ‘is it valid to continue?’

At any rate, here is my test code that PHP method chaining works great:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class foo
{
    public function bar()
    {
        print 'bar<br />';
        return $this;
    }

    public function splat()
    {
        print 'splat!<br />';
        return $this;
    }

    public function twin()
    {
        return $this->single();
    }

    public function single()
    {
        print 'single<br />';
        return $this;
    }

    public function neato()
    {
        print 'neato';
        return $this;
    }
}

$ohNo = new foo();
$ohNo->bar()->splat();
$ohNo->twin()->neato();

As expected, the output is:

bar
splat!
single
neato

Each of these methods are pretty self explanatory. The only one that is slightly different is the twin()/single() methods. Note how the twin() method is returning the value of another method directly. The chain remains solid and connected.

This entry was posted in PHP, programming and tagged , . Bookmark the permalink.

One Response to chaining methods in PHP

  1. Dave Rowe says:

    Chaining is very cool. It’s great to see major libraries using it. I was first really introduced to it by jQuery, and just thought “This is smart”. Then, I see Doctrine uses it, very cool.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>