18

检查 Zend 框架,我发现所有 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;
}

等等。每个公共二传手都返回$this。它不仅适用于 setter,还有其他操作方法返回$this

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

为什么需要这个?退货$this有什么用?它有什么特殊含义吗?

4

2 回答 2

47

return $this允许链接方法,例如:

$foo->bar('something')->baz()->myproperty
于 2012-06-17T16:35:13.297 回答
4

这样就可以像这样“链接”对象上的方法调用。

$obj -> setFoo ('foo') -> setBar ('bar') -> setBaz ('baz') -> setFarble ('farble');
于 2012-06-17T16:36:24.060 回答