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

2021-12-29 00:00:00 return php zend-framework getter-setter

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

Examining Zend Framework, I found that all setter methods (of those I’ve examined) return the instance of the class it lives in. It doesn't only set a value but also returns $this. For example:

  /*   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;
}

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

And so on. Every public setter returns $this. And it's not only for setters, there are also other action methods that return $this:

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

为什么需要这个?返回 $this 有什么作用?有什么特殊含义吗?

Why is this needed? What does returning $this do? Does it have some special meaning?

推荐答案

return $this 允许链接如下方法:

$foo->bar('something')->baz()->myproperty

相关文章