PHP OOP: Chainable objects?
Asked Answered
P

3

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!

Panatella answered 28/5, 2010 at 14:37 Comment(0)
C
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.

Cornhusk answered 28/5, 2010 at 14:39 Comment(1)
Amazing how easy this was to do. Had no idea. Thanks a lot Gumbo!Panatella
C
11

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

function add() {
    // other code
    return $this;
}
Content answered 28/5, 2010 at 14:39 Comment(0)
B
5

Another term for this is the Fluent Interface

Badalona answered 28/5, 2010 at 15:7 Comment(1)
Adding a note: method chaining is but one technique in creating a fluent interface.Bealle

© 2022 - 2024 — McMap. All rights reserved.