本文介紹了為什么在 setter 方法中返回 $this ?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
檢查 Zend 框架,我發(fā)現(xiàn)所有的 setter 方法(我檢查過的)都返回它所在類的實例.它不僅設(shè)置一個值,還返回 $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
這篇關(guān)于為什么在 setter 方法中返回 $this ?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!