“return $this”是什么意思?意思是?
我试图理解这段代码,但当我到达最后一行时,我没有明白。 :(
我可以请你帮忙看看 return $this
是什么意思吗?
public function setOptions(array $options) {
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
//???? - return what ?
return $this;
}
更新:
为了更好地澄清,我删除了我的评论。
I'm trying to understand this code, and when I arrived at the final line, I didn't get it. :(
Can I have your help in order to find out, what does return $this
mean ?
public function setOptions(array $options) {
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
//???? - return what ?
return $this;
}
Update:
I've removed my comments for better clarification.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这种编码方式称为流畅界面。
return $this
返回当前对象,因此您可以编写如下代码:而不是:
This way of coding is called fluent interface.
return $this
returns the current object, so you can write code like this:instead of:
这将返回调用该方法的实例。这通常是为了实现流畅的接口,这样你就可以调用类似的东西:
其中
setOptions< /code> 和
sayHello
将在同一个对象上调用。This will return the instance this method is called on. This usually done for achieving fluent interfaces so you can call stuff like:
Where both
setOptions
andsayHello
would be called on the same object.$this
表示当前对象,即当前正在运行该方法的对象。通过返回$this
对正在工作的对象的引用,该方法将被发送回调用函数。所以任何人现在做
$foo2 也指 $foo 。
$this
means the current object, the one the method is currently being run on. By returning$this
a reference to the object the method is working gets sent back to the calling function.So anyone doing
$foo2 now refers to $foo also.
你只需创建一个函数链
,这样你就可以使用它
you just can create a function chain
so you can use this
$this 将是包含该函数的类。
因此,如果您像这样调用它:
$obj->setOptions($options)
它将返回 $obj,它已使用新选项设置。通常,当这样设置时,您不必捕获返回,因为它会影响对象本身,但它会影响对象本身,因此您可以内联使用它。
$this would be the class that contains that function.
So if you were to call it like:
$obj->setOptions($options)
it's going to return $obj, which has been set with the new options. Generally when something is set like this, you don't have to capture the return, because it's affecting the object itself, but it makes it so you can use it inline.
如果 SetOptions 方法是 ProgramOptions 类或其他类的一部分,则 $this 将引用包含该方法的类,因此您将传回 ProgramOptions 的实例。
If the SetOptions method is part of a ProgramOptions class or something, $this would refer to the class containing the method, so you would be passing back an instance of ProgramOptions.
它是一种常见的 OOP 技术,称为Fluent Interface。它的主要目的是帮助在不支持方法级联的语言(如 PHP)中链接多个方法调用。所以
将返回该类的更新实例(对象),以便它可以在其范围内进行另一个调用。请参阅 PHP 中的示例,
Its a common OOP technique called Fluent Interface. It main purpose to help chain multiple method calls in languages, that do not support method cascading, like PHP. So
will return an updated instance(object) of that class so it can make another call in its scope. See example in PHP,