gpt4 book ai didi

php - 为什么要在 setter 方法中返回 $this?

转载 作者:IT王子 更新时间:2023-10-29 00:10:37 25 4
gpt4 key购买 nike

检查 Zend Framework,我发现所有 setter 方法(在我检查过的方法中)都返回它所在的类的实例。它不仅设置一个值,还返回 $this。例如:

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

等等。每个公共(public) setter 都返回 $this。而且它不仅针对 setter,还有其他返回 $this 的操作方法:

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

为什么需要这个?返回 $this 有什么作用?有什么特殊的含义吗?

最佳答案

return $this 允许链接方法,例如:

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

关于php - 为什么要在 setter 方法中返回 $this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11072965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com