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

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

问题描述

可能的重复:
PHP 将所有参数作为数组获取?

嗯,

在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天全站免登陆