如何在PHP中用单行调用两个方法? [英] how to call two method with single line in php?
问题描述
我已经在幼虫中看到了在单行示例中调用多种方法的情况
I have seen in larval calling multiple method in the single line example
DB:: get ('test') ->toJson ();
我有一个很棒的课程,并且该课程中有一个view方法.
I have a cool class and view method in that class.
$this->call->view ('welcome') ->anotherMethod ();
我还要调用另一个方法吗?我应该在哪里做这种方法?
I would like to call another method also? Where should I make that method?
推荐答案
DB::get()
似乎是一种返回对象的方法,您可以在其中调用其他函数(我认为是数据库查询的结果对象).如果要在一行中的一个对象上调用多个函数,则必须在函数中返回$this
,例如:
DB::get()
seems to be a method returning an object, where you can call other functions (I think a result object of a database query). If you want to call multiple functions on one object in one line, you have to return $this
in your functions, e.g.:
class View {
public static function factory {
// The question is: How useful is this factory function. In fact: useless in
// the current state, but it can be extended in any way
return new self;
}
public function one() {
// do something
return $this;
}
public function two() {
// do something
return $this;
}
}
那么你可以做:
$class = new View();
$class->one()->two();
// it's also possible to use the `factory` function
// you should think about, how useful this approach is in your application
$class = View::factory()->one()->two();
这就是您可以在php中完成的方法,如果laravel有一些帮助者,我不能说:)
That's how you can do it in php, if laravel has some helpers for that, i can't say :)
这篇关于如何在PHP中用单行调用两个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!