Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I chain methods in PHP? [duplicate]

Tags:

jQuery lets me chain methods. I also remember seeing the same in PHP so I wrote this:

class cat {  function meow() {  echo "meow!";  }  function purr() {  echo "purr!";  } }  $kitty = new cat;  $kitty->meow()->purr(); 

I cannot get the chain to work. It generates a fatal error right after the meow.

like image 242
netrox Avatar asked Sep 25 '11 23:09

netrox


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 method chaining in laravel?

Method chaining interface allows you to chain method calls, which results in less typed characters when applying multiple operations on the same object. Using method chaining.

What is chaining methods in JavaScript?

Method Chaining is a programming strategy that simplifies and embellishes your code. It is a mechanism of calling a method on another method of the same object. this keyword in JavaScript refers to the current object in which it is called.


2 Answers

To answer your cat example, your cat's methods need to return $this, which is the current object instance. Then you can chain your methods:

class cat {  function meow() {   echo "meow!";   return $this;  }   function purr() {   echo "purr!";   return $this;  } } 

Now you can do:

$kitty = new cat; $kitty->meow()->purr(); 

For a really helpful article on the topic, see here: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

like image 178
Zachary Murray Avatar answered Sep 29 '22 14:09

Zachary Murray


Place the following at the end of each method you wish to make "chainable":

return $this; 
like image 28
Tim Cooper Avatar answered Sep 29 '22 12:09

Tim Cooper