开发者

How do I chain methods in PHP? [duplicate]

This question alre开发者_开发问答ady has answers here: PHP method chaining or fluent interface? (10 answers) Closed 7 years ago.

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.


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;


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();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜