Why return $this in setter methods?

若如初见. 提交于 2019-12-30 03:49:10

问题


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

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

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


回答1:


The return $this allows the chaining of methods like:

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



回答2:


It's so that method calls on an object can be "chained", like this.

$obj -> setFoo ('foo') -> setBar ('bar') -> setBaz ('baz') -> setFarble ('farble');


来源:https://stackoverflow.com/questions/11072965/why-return-this-in-setter-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!