Page 1 of 1

What does $this->somefunc()->someotherfunc() do ?

Posted: Tue Aug 31, 2010 10:57 pm
by sammonster
I've seen code where the usage is something like this:

Code: Select all

public function foo() {
  $this->somefunction("test string")->somefunction("test string2")->someotherfunction(1);
}
I didn't think you could do this in php (ie: call a method from the result of another method) like this. Is there a specific name for doing this? I see it all the time in Zend's Framework.

Example from Zend:

Code: Select all

$form->setAction('/user/login')
    ->setMethod('post')
    ->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
Any help with explaining this would be greatly appreciated!

Re: What does $this->somefunc()->someotherfunc() do ?

Posted: Tue Aug 31, 2010 11:06 pm
by requinix
"Method chaining", most commonly. There's nothing really special about it - it's like shorthand, that's all.

Re: What does $this->somefunc()->someotherfunc() do ?

Posted: Tue Aug 31, 2010 11:13 pm
by sammonster
Thanks. Is there a reason why someone would want to chain methods like this versus just doing it the same way it's been done for eons? or is it just the concept of "using something new"

Re: What does $this->somefunc()->someotherfunc() do ?

Posted: Wed Sep 01, 2010 12:42 am
by requinix
Zend Framework especially touts it as a "feature". For "cleaner code" and other lies.

There's no PHP benefit to using it. It's all style. If you like it, use it, and if you don't, then don't.

Re: What does $this->somefunc()->someotherfunc() do ?

Posted: Wed Sep 01, 2010 7:46 am
by sammonster
That's what I thought. Thanks man.