Why return $this in setter methods?(为什么在 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 允许链接如下方法:
$foo->bar('something')->baz()->myproperty
这篇关于为什么在 setter 方法中返回 $this ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 setter 方法中返回 $this ?
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
