【问题标题】:Add Arguments to Existing PHP Function from Array从数组向现有 PHP 函数添加参数
【发布时间】:2016-02-10 08:20:16
【问题描述】:

我正在寻找如何为基于数组的函数调用添加更多参数,但不知道我需要做什么。有问题的函数不能简单地传递一个数组,但是数组必须以某种方式爆炸,就好像每个数组元素都是函数调用中的一个新参数一样。我不认为 call_user_func_array 有效,但也许我不知道如何正确执行它。为了给出一些上下文,参数数组来自不同数量的 $_GET 参数,这些参数由我无法控制的 API 类文件处理,但似乎我可以添加很多参数来过滤结果.

$arrayofarguments = array("dynamicarg1","dynamicarg2","dynamicarg3");

$runthis = example($staticargument1,
                 $staticargument2,
                 $staticargument3,
                 $arrayofarguments,
                 $staticargument4); 

//run the results
echo $runthis;

预期结果

$runthis = example($staticargument1,
                 $staticargument2,
                 $staticargument3,
                 "dynamicarg1",
                 "dynamicarg2",
                 "dynamicarg3",
                 $staticargument4);

感谢您的帮助! :)

【问题讨论】:

    标签: php arrays function arguments


    【解决方案1】:

    我认为你必须做类似的事情

    function example("blaa","foo","bar",$arrayofarguments,"test") {
    
      $args = func_get_args();
    
      // $arg[3] would be $arrayofarguments
      foreach ( $arg[3] as $function) {
        $function(); // this calls the function
      }
    }
    

    【讨论】:

    • 它确实符合 OPs 要求(只要它有效):/
    • 我想指出的是,从 GET 接受和运行任意函数名称是非常危险。如果你不能改变这一点,至少你应该实现一个允许功能的白名单。
    • 谢谢!我现在意识到我应该更符合这个条件。如果我无法访问实际功能,我该怎么办?鉴于此,我将编辑我的问题。所以情况是没有函数但调用 example() 函数但无法编辑它。
    • @Dyluck if (function_exists($function)) { $fuction(); } 只会在函数存在时调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 2016-08-11
    相关资源
    最近更新 更多