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

2022-01-19 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 允许链接方法,例如:

The return $this allows the chaining of methods like:

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

相关文章