PHP -使用方法链接来扩展先前的方法


PHP - use method chaining to extends previous method

我怎么能做额外的方法(如Laravel),扩展先前的链接?例如:

$page->loadFooter()->withExtension("script_name")withExtension()为附加法,对loadFooter()法的结果有何影响?

方法链的工作方式是每次调用必须返回对象本身(即$this)。

所以你的页面类定义看起来像:

class Page {
    public function loadFooter() {
        /* ... */
        return $this;
    }
    public function withExtension($script) {
        /* ... */
        return $this;
    }
}

方法链中实际发生的是下一个函数在返回的对象上被调用。

在你的函数中你返回一个对象,通常是$this

class Page {
    public $footer;
    public function loadFooter() {
        $this->footer = file_get_contents("footer.html");
        return $this;
    }
    public function withExtension($script) {
        $this->footer = str_replace($this->footer, "</body>", "<script src='{$script}'></script></body>");
    }
}
$page = new Page();
$page->loadFooter()->withExtension("script name");

loadFooter()只需要返回一个具有withExtension方法的对象。所以如果你想影响$page对象,那么loadFooter应该返回它的对象。

/*Within $page's class*/
public function loadFooter(){
  /**insert Code**/
  return $this;
}