我想知道php是如何实现如下功能设计的:
类->func()->func()
这是 laravel 验证示例。
$validator->after(function($validator)
{
if ($this->somethingElseIsInvalid())
{
**$validator->errors()->add('field', 'Something is wrong with this field!');**
}
});
after() 在这里发挥神奇作用吗?
以及如何创建我自己的代码来表现得像这样。
最佳答案
它称为方法链。
方法链接之所以有效,是因为类的函数或方法总是返回进一步调用另一个函数的对象。
基本上它会自行返回。
例如:
public function method1() {
// method content ...
return $this;
}
public function method2() {
// method content ...
return $this;
}
请引用以下链接以阅读有关方法链的更多信息,
http://www.techflirt.com/tutorials/oop-in-php/php-method-chaining.html
您可以找到更多关于此的文章。
关于php调用嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39504517/