本文介绍了为什么在 setter 方法中返回 $this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检查 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
这篇关于为什么在 setter 方法中返回 $this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!