How do I chain methods in PHP? [duplicate]

瘦欲@ 提交于 2019-11-27 14:19:24
Zachary Murray

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!