Green Green - 7 months ago 13
PHP Question

Why to do return $this in setter methods?

Examining Zend Framework I found that every setter method of any of its class (of those I’ve examined) returns the instance of the class it lives in. Not just sets some value but sets a value and 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 not only setters, there are also some action methods, they also returns $this:

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


What for is this needed? What does return of $this do? Does it have some special meaning?

Answer

The return $this allows the chaining of methods like:

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

Check out to learn more: