Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OOP: Chainable objects?

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!

like image 814
Industrial Avatar asked May 28 '10 14:05

Industrial


People also ask

What is method chaining in PHP?

Method chaining is a fluent interface design pattern used to simplyify your code. If you've used frameworks like Zend or jQuery, you probably have some experience with chaining. Essentially your objects return themselves, allowing you to "chain" multiple actions together.

What is chaining in programming?

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.


2 Answers

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.

like image 128
Gumbo Avatar answered Sep 19 '22 18:09

Gumbo


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

function add() {
    // other code
    return $this;
}
like image 35
Victor Stanciu Avatar answered Sep 21 '22 18:09

Victor Stanciu