8

I have tried to find a good introduction on chainable OOP objects in PHP, but without any good result yet.

How can something like this be done?

$this->className->add('1','value');
$this->className->type('string');
$this->classname->doStuff();

Or even: $this->className->add('1','value')->type('string')->doStuff();

Thanks a lot!

Charles
  • 50,943
  • 13
  • 104
  • 142
Industrial
  • 41,400
  • 69
  • 194
  • 289

3 Answers3

17

The key is to return the object itself within each method:

class Foo {
    function add($arg1, $arg2) {
        // …
        return $this;
    }
    function type($arg1) {
        // …
        return $this;
    }
    function doStuff() {
        // …
        return $this;
    }
}

Every method, that returns the object itself, can be used as an intermediate in a method chain. See Wikipedia’s article on Method chaining for some further details.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
11

just return $this in the add() and type() methods:

function add() {
    // other code
    return $this;
}
Victor Stanciu
  • 12,037
  • 3
  • 26
  • 34
5

Another term for this is the Fluent Interface

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Adding a note: method chaining is but one technique in creating a fluent interface. – koen May 28 '10 at 19:29