【问题标题】:How do I chain methods in PHP? [duplicate]如何在 PHP 中链接方法? [复制]
【发布时间】:2011-11-24 20:27:45
【问题描述】:

jQuery 让我可以链接方法。我还记得在 PHP 中看到过同样的情况,所以我写了这个:

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

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

$kitty = new cat;

$kitty->meow()->purr();

我无法让链条工作。它在喵喵叫之后立即产生一个致命错误。

【问题讨论】:

  • kitty 的例子更能说明问题 ;-)

标签: php methods method-chaining


【解决方案1】:

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

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

 function purr() {
  echo "purr!";
  return $this;
 }
}

现在你可以这样做了:

$kitty = new cat;
$kitty->meow()->purr();

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

【讨论】:

【解决方案2】:

将以下内容放在您希望“可链接”的每个方法的末尾:

return $this;

【讨论】:

    【解决方案3】:

    只需从您的方法中返回 $this,即(对)对象本身的(引用):

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

    现在您可以尽情链接了:

    $x = new Foo;
    $x->f()->f()->f();
    

    【讨论】:

      【解决方案4】:

      是的,使用 php 5 您可以从方法返回对象。所以通过返回$this(指向当前对象),就可以实现方法链接

      【讨论】:

      • 为什么这被否决了?和其他人一样的答案......
      猜你喜欢
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 2014-02-10
      • 2012-10-22
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      相关资源
      最近更新 更多