dongpao1083 2018-09-05 09:58
浏览 15
已采纳

一个Liner在PHP中使用相同的参数调用多个函数

I have 2 or more functions that always takes the same arguments. The argument is the returned value of another function call.

This is the code:

$result = getMyResult();

myFunction1($result);
myFunction2($result);
...

Question

Is there a way to call multiple functions on the same line with the same argument?

An example of what I'm trying to achieve:

myFunction1,myFunction2...(getMyResult());

Demands

  • The solution can be procedural or object oriented.
  • I don't want to temporary store the returned value of getMyResult() in a variable.
  • I only want to call getMyResult() once.
  • I don't want to wrap the function calls in a helper function *

* like this.

function myHelperFunction($result) {
    myFunction1($result);
    myFunction2($result);
    ...
}

If myHelperFunction() is the closest solution, then I'm happy to hear about it.

  • 写回答

1条回答 默认 最新

  • douchao1957 2018-09-05 13:21
    关注

    I've done some more research and the closest I´ve been able to come to an answer that lives up to my requirements is with 1: an object oriented approach and fluent setters or 2: with a helper function.

    (Found Solution 1 here: Call multiple methods on object?)

    Solution 1 (3/4 requirements) Make a class with methods and have every method return the object itself.

    $result = getMyResult();
    $myclass->myMethod1($result)->myMethod2($result)->...
    

    The only "problem" is that I have to store the argument in a temp variable because I don't want to call getMyResult() more than once.

    Solution 2 (3/4 requirements) Helper function procedural solution.

    function myHelperFunction($result) {
        myFunction1($result);
        myFunction2($result);
        ...
    }
    
    myHelperFunction(getMyResult());
    

    The only "problem" is that I have to define a function that calls all my other functions. This function is not dynamic because I can not control the number of functions called inside without implemententing further logic.

    Conclusion

    I can't find any solution that meets all my reqiurements and I can't determine if there is another solution out there at this point. Both Solution 1 and 2 would make designing my code easier. For now I will settle with Solution 1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么