1

Possible Duplicate:
PHP Method chaining Confusion

If i have a php class

class ClassName {
    function f1() {
        //...
    }
    function f2() {
        //...
    }
}
$cn = new ClassName();

How to define the class that i can use functions in style

$cn->f1()->f2();

instead of

$cn->f1();
$cn->f2();

Thank you.

Community
  • 1
  • 1
iff
  • 192
  • 6
  • 14

2 Answers2

6
class ClassName {
    public function f1() {
        //...
        return $this;
    }
    public function f2() {
        //...
        return $this;
    }
    // and for a static
    public static function sf1() {
        // ...
        return self;
    }
}

But, method chaining is a bad idea. It makes for hard to read code.

If you are returning an instance of the same object, it is not directly harmful. But, when you start writing code like $locator->get('MySQL')->connection()->query('SELECT 1');, then it is possible that people who are stuck maintaining your code will find where you live and punish you.

Also, if you are going by "but jquery does it" reasoning, I am sorry to inform you, but that - more often than not - is a sign that something is a bad practice.

Statik Stasis
  • 308
  • 1
  • 5
  • 16
tereško
  • 58,060
  • 25
  • 98
  • 150
  • 2
    I think method chaining can be a good idea because it makes certain code easier to read. – erisco Aug 12 '12 at 06:50
  • 2
    @erisco , in some very specific cases, and if you are sticking to same instance - yes, you are right. But the general rule of thumb is: *"Avoid It"*. – tereško Aug 12 '12 at 06:54
  • its very bad.. probably thats why Zend frameworks uses this in all of its setters – mschr Aug 12 '12 at 07:02
  • Please cite a discussion that illustrates or otherwise showcases why method chaining should be avoided. I haven't heard of this. – erisco Aug 12 '12 at 07:06
  • @mschr , and of course we all know that Zend Framework is such a [collection](https://github.com/zendframework/zf2/blob/master/library/Zend/Serializer/Adapter/PhpCode.php#L47) [of](https://github.com/zendframework/zf2/blob/master/library/Zend/EventManager/StaticEventManager.php#L51) [best](https://github.com/zendframework/zf2/blob/master/library/Zend/Http/Header/CacheControl.php#L177) [practices](https://github.com/zendframework/zf2/blob/master/library/Zend/Di/Di.php#L466). – tereško Aug 12 '12 at 07:28
  • @erisco , http://stackoverflow.com/questions/10571009/one-lined-class-functions-do-or-dont – tereško Aug 12 '12 at 07:33
4

To have chaining in functions you need to return current object from the function..

return $this;

add this in your function f1()..

class ClassName {
    function f1() {
        //...
        return $this;
    }
    function f2() {
        //...
        return $this;
    }
}
Rajat Singhal
  • 11,234
  • 5
  • 38
  • 56