23

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.

matsjoyce
  • 5,744
  • 6
  • 31
  • 38
netrox
  • 5,224
  • 14
  • 46
  • 60

4 Answers4

41

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

halfer
  • 19,824
  • 17
  • 99
  • 186
Zachary Murray
  • 1,220
  • 9
  • 16
  • 1
    Article gone. Here is [the last working archive](https://web.archive.org/web/20130417023845/http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html). – Majid Fouladpour Dec 01 '15 at 08:27
7

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

return $this;
4

Just return $this from your method, i.e. (a reference to) the object itself:

class Foo()
{
  function f()
  {
    // ...
    return $this;
  }
}

Now you can chain at heart's content:

$x = new Foo;
$x->f()->f()->f();
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

yes using php 5 you can return object from a method. So by returning $this (which points to the current object), you can achieve method chaining

Albert Xing
  • 5,620
  • 3
  • 21
  • 40