php函数中的动态参数 [英] dynamic arguments in php function

查看:170
本文介绍了php函数中的动态参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
PHP是否将所有参数作为数组?

Possible Duplicate:
PHP get all arguments as array?

好吧

在Java中,我可以执行此操作(伪代码):

In java I can do this (pseudocode):

public hello( String..args ){
    value1 = args[0] 
    value2 = args[1] 
    ...
    valueN = arg[n];
}

然后:

hello('first', 'second', 'no', 'matter', 'the', 'size');

php中是否有类似的东西?

Is something like this in php?

编辑

我现在可以传递一个像hello(array(bla, bla))这样的数组,但是可能以上面提到的方式存在,对吧?

I now that I can pass an array like hello(array(bla, bla)), but may could exists the way mencioned above, right?

推荐答案

请参见 func_get_args :

function foo()
{
    $numArgs = func_num_args();

    echo 'Number of arguments:' . $numArgs . "\n";

    if ($numArgs >= 2) {
        echo 'Second argument is: ' . func_get_arg(1) . "\n";
    }

    $args = func_get_args();
    foreach ($args as $index => $arg) {
        echo 'Argument' . $index . ' is ' . $arg . "\n";

        unset($args[$index]);
    }
}

foo(1, 2, 3);

编辑1

当您调用foo(17, 20, 31) func_get_args()时,例如,不知道第一个参数代表$first变量.当您知道每个数字索引代表什么时,您可以执行此操作(或类似操作):

When you call foo(17, 20, 31) func_get_args() don't know that the first argument represents the $first variable for example. When you know what each numeric index represents you can do this (or similar):

function bar()
{
    list($first, $second, $third) = func_get_args();

    return $first + $second + $third;
}

echo bar(10, 21, 37); // Output: 68

如果我想要一个特定的变量,我可以省略其他变量:

If I want a specific variable, I can ommit the others one:

function bar()
{
    list($first, , $third) = func_get_args();

    return $first + $third;
} 

echo bar(10, 21, 37); // Output: 47

这篇关于php函数中的动态参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆