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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sammonster
Forum Newbie
Posts: 6
Joined: Tue Aug 31, 2010 10:51 pm

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

Post 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!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post by requinix »

"Method chaining", most commonly. There's nothing really special about it - it's like shorthand, that's all.
sammonster
Forum Newbie
Posts: 6
Joined: Tue Aug 31, 2010 10:51 pm

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

Post 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"
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
sammonster
Forum Newbie
Posts: 6
Joined: Tue Aug 31, 2010 10:51 pm

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

Post by sammonster »

That's what I thought. Thanks man.
Post Reply