PHP将数组值解析为函数

问题描述:

好吧,我有一个带有2个强制参数的函数,然后它也必须有许多可选参数。PHP将数组值解析为函数

function example($a,$b, $username, $email) { 
    // code 
} 

我对可选参数数据来自数组

$x = array('joeblogs', '[email protected]'); 

我怎么会能够解析这些?记住可能需要该函数来每次解析不同的参数集合。

一个例子是使用CakePHP可以指定所需

以下示出的语法可选参数和默认值

function example($a,$b, $username = '', $email = '') { 

} 

另一种可能性是通过一种“可选值数组”

操作的参数
function example($a,$b, $optional_values = array()) { 
    if($optional_values[0] != '') { blah blah .... } 
} 

像这样?

$a = 'a'; 
$b = 'b'; 
$x = array('joeblogs', '[email protected]'); 

$args = array_merge(array($a, $b), $x); 

call_user_func_array('example', $args); 

http://php.net/manual/en/function.call-user-func-array.php

有两种方法可选参数。

在第一个,你指定所有的这样的论点:

function example($a, $b, $c=null, $d=null, $e=null) 

参数$a$b是必需的。其他是可选的,如果没有提供,则是null。该方法要求按照指定的顺序指定每个可选参数。如果你想只使用$a$b$e调用该方法你必须为$c$d提供空值:

example($a, $b, null, null, $d); 

第二种方法接受一个数组作为第三个参数。这个阵列会基于找到的钥匙检查钥匙和处理:

function example($a, $b, $c=array()) { 

    $optionalParam1 = (!empty($c['param1'])) : $c['param1'] ? null; 
    $optionalParam2 = (!empty($c['param2'])) : $c['param2'] ? null; 

通过这种方式,您可以检查可提供的每个键。将为未填充的任何键提供空值。

通过简单构建所需的语句并对其进行评估,可以使用eval()找到一个工作解决方案。

生成的参数:

foreach($arguments as &$i) { 
     $i = str_pad($i, (strlen($i) + 2), "'", STR_PAD_BOTH); 
    } 
    $getVars = implode(', ', $arguments); 

&则:

eval('$controller->$action('.$getVars.');'); 

这是一个 '黑客' 或将是稳定的? 似乎参数会根据需要进行解析。

+0

的eval是邪恶的。当真的有必要的时候没有太多情况,我知道只有两个:混淆和编程,当你喝醉 – pinepain 2013-05-10 19:04:18

+0

所有的建议是传递一个数组,这不是我所需要的,所以我想这是必须的 – Callum 2013-05-10 22:58:48

该解决方案是您的消解和Jez解决方案的合并。

call_user_func_array(array($controller, $action), $getVars); 

哪里$controller是控制器的情况下,$action是字符串要打电话的动作,而$getVars是参数数组。

call_user_func_array函数的第一个参数是一个回调。可以将方法调用定义为回调。

这里是一个PHP的回调的文档的链接:http://www.php.net/manual/pt_BR/language.pseudo-types.php#language.types.callback

要通过数组参数的功能,您可以使用call_user_func_array

$args = array('foo', 'bar', 'joeblogs', '[email protected]'); 
call_user_func_array('example', $args); 

或者简单的通过任意数量的参数:

example($a, $b, $username, $email); 

检索函数内部的参数使用func_get_args

function example() { 
    $args = func_get_args(); 

    print_r($args); 

    // output: 
    // Array ( 
    //  [0] => foo 
    //  [1] => bar 
    //  [2] => joeblogs 
    //  [3] => [email protected] 
    // ) 

}