是否可以计算PHP函数中缺少的参数?我想这样做:
// I have this
function foo($param1, $param2, $param3) {
// I need some sort of argument counter
}
foo("hello", "world");
当我像上面这样使用 foo 函数时,我想要一种方法来找出并非所有参数都被使用。
要么计算所有参数并与 get_defined_vars() 进行比较,要么使用一个函数来计算缺少的参数。
编辑:如果打开error_reporting时缺少某些参数,我需要该方法停止运行。
if(!foo($param)) { echo "Couldn't Foo!"; }
使用 func_num_args()
如果要执行此超动态操作,请使用反射来获取预期的参数计数,并将该数字与 func_num_args() 返回的数字进行比较:
function foo($p1 = null, $p2 = null, $p3 = null) {
$refl = new ReflectionFunction(__FUNCTION__);
$actualNumArgs = func_num_args();
$expectedNumArgs = $refl->getNumberOfParameters();
$numMissingArgs = $expectedNumArgs - $actualNumArgs;
// ...
调用参数不足的函数将引发错误。如果需要允许调用具有较少参数的函数,则需要在函数声明中使用默认值定义它们,并测试默认值以查看已省略的默认值。
像这样的东西(再次改进):
function foo () {
// Names of possible function arguments
// This replaces the list of arguments in the function definition parenthesis
$argList = array('param1', 'param2', 'param3');
// Actual function arguments
$args = func_get_args();
// The number of omitted arguments
$omittedArgs = 0;
// Loop the list of expected arguments
for ($i = 0; isset($argList[$i]); $i++) {
if (!isset($args[$i])) { // The argument was omitted - this also allows you to skip arguments with NULL since NULL is not counted as set
// increment the counter and create a NULL variable in the local scope
$omittedArgs++;
${$argList[$i]} = NULL;
} else {
// The argument was passed, create a variable in the local scope
${$argList[$i]} = $args[$i];
}
}
// Function code goes here
var_dump($omittedArgs);
}
对于可能维护代码的其他人来说,这有点违反直觉 - 参数列表现在维护为字符串数组而不是函数参数列表,但除此之外,它是完全动态的,可以实现您想要的。
根据您的需要,最简单的解决方案可能是默认参数:
function foo($param1 = null, $param2 = null, $param3 = null) {
if ($param3 !== null) {
// 3 params are specified
} else if ($param2 !== null) {
// 2 params are specified
} else if ($param1 !== null) {
// 1 param is specified
} else {
// no param is specified
}
}
您可以使用内置的 php 函数:
参数数组:http://php.net/manual/en/function.func-get-args.php
参数数:http://php.net/manual/en/function.func-num-args.php
从数组中获取参数http://php.net/manual/en/function.func-get-arg.php