为什么在setter方法中返回$ this?

Gre*_*een 17 php zend-framework return getter-setter

通过检查Zend Framework,我发现所有setter方法(我已经检查过的方法)都会返回它所在类的实例.它不仅设置了一个值,还返回了它$this.例如:

  /*   Zend_Controller_Router   */
public function setGlobalParam($name, $value) {
    $this->_globalParams[$name] = $value;
    return $this;
}

  /*    Zend_Controller_Request    */
public function setBaseUrl($baseUrl = null) {
    // ... some code here ...
    $this->_baseUrl = rtrim($baseUrl, '/');
    return $this;
}

  /*    Zend_Controller_Action    */
public function setFrontController(Zend_Controller_Front $front) {
    $this->_frontController = $front;
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

等等.每个公共制定者都会回来$this.并且它不仅适用于setter,还有其他返回的操作方法$this:

public function addConfig(Zend_Config $config, $section = null) {
    // ... some code here ...
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

为什么需要这个?回来$this做什么?它有一些特殊含义吗?

Sar*_*raz 42

return $this允许的类似方法的链接:

$foo->bar('something')->baz()->myproperty
Run Code Online (Sandbox Code Playgroud)