我对此困惑了一段时间,
如何在 PHP 中以流畅的界面执行最后一个函数调用后的函数?
例如,如果我有一个像这样实例化和链接的类:
$myclass->function1()->function2()->function3();
是否有办法在连贯界面中使用的最后一个函数之后执行一段代码?它可能是 function1()、function2() 或 function3()...
我需要保持这条线不变:
$myclass->function1()->function2()->function3();
我无法使用:
$myclass->function1()->function2()->function3()->afterFunctions();
也不
$myclass->function1()->function2()->function3().""; // to trigger __toString()
并且可以调用任意数量的链式函数,即
$myclass->function1()->function2();
我想也许我可以使用
__destroy()
魔术函数,但这行不通,因为在同一范围内可能会多次调用该类,即
function test() {
$myclass = new Class1();
$myclass->function1()->function2()->function3();
$myclass2 = new Class1();
$myclass2->function2()->function3()->function1();
}
可能有一个我不知道的神奇函数可以帮助实现流畅的接口链式类的最终函数。
对此有任何帮助,我们将不胜感激。
您只需要在每个方法中
return $this;
,这样您就可以返回对象,因此您可以在其上调用另一个方法:
class Test {
function method1(): Test {
// logic
return $this;
}
function method2(): Test {
// logic
return $this;
}
}
$obj = new Test;
$obj->method1()->method2();