如何在PHP中链接方法?

net*_*rox 23 php methods method-chaining

jQuery让我链接方法.我还记得在PHP中看到相同的内容所以我写了这个:

class cat {
 function meow() {
 echo "meow!";
 }

function purr() {
 echo "purr!";
 }
}

$kitty = new cat;

$kitty->meow()->purr();
Run Code Online (Sandbox Code Playgroud)

我不能让链条起作用.它会在喵喵之后产生致命错误.

Zac*_*ray 41

要回答你的cat示例,你的cat的方法需要返回$this,这是当前的对象实例.然后你可以链接你的方法:

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

 function purr() {
  echo "purr!";
  return $this;
 }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

$kitty = new cat;
$kitty->meow()->purr();
Run Code Online (Sandbox Code Playgroud)

有关该主题的非常有用的文章,请参见此处:http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html


Tim*_*per 7

在您希望制作"可链接"的每种方法的末尾放置以下内容:

return $this;
Run Code Online (Sandbox Code Playgroud)