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

Why return $this in setter methods?(为什么在 setter 方法中返回 $this?)
本文介绍了为什么在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)