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

一个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.

我有两个或更多的函数总是采用相同的参数。 参数是另一个函数调用的返回值。 p>

这是代码: strong> p>

  $ result  = getMyResult(); 
 
myFunction1($ result); 
myFunction2($ result); 
 ... 
  code>  pre> 
 
 

问题 strong > p>

有没有办法用相同的参数在同一行上调用多个函数? p>

我是什么的一个例子 试图实现: em> p>

  myFunction1,myFunction2 ...(getMyResult()); 
  code>  pre> 
 
 

需求 em> p>

  • 解决方案可以是程序性的或面向对象的。 li>
  • 我不想暂时 将 getMyResult() code>的返回值存储在变量中。 li>
  • 我只想调用 getMyResult() code>一次。 li> \ n
  • 我不想将函数调用包装在辅助函数中* li> ul>

    *像这样。 p>

      function myHelperFunction($ result){
     myFunction1($ result); 
     myFunction2($ result); 
     ... 
    } 
      code>  pre> 
     
      如果我的 HelperFunction() code>是最接近的解决方案,我很高兴听到它。 em>  p> 
      div>

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.