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.
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.
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.
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.
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
Place the following at the end of each method you wish to make "chainable":
return $this;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With