How to work with infinity arguments in a function (like PHP's isset())

自作多情 提交于 2019-11-30 07:59:15

func_get_args will do what you want:

function infinite_parameters() {
    foreach (func_get_args() as $param) {
        echo "Param is $param" . PHP_EOL;
    }
}

You can also use func_get_arg to get a specific parameter (it's zero-indexed):

function infinite_parameters() {
    echo func_get_arg(2);
}

But be careful to check that you have that parameter:

function infinite_parameters() {
    if (func_num_args() < 3) {
        throw new BadFunctionCallException("Not enough parameters!");
    }
}

You can even mix together func_*_arg and regular parameters:

function foo($param1, $param2) {
    echo $param1; // Works as normal
    echo func_get_arg(0); // Gets $param1
    if (func_num_args() >= 3) {
        echo func_get_arg(2);
    }
}

But before using it, think about whether you really want to have indefinite parameters. Would an array not suffice?

Starting with PHP 5.6 you can use the token "..."

Example:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

Source: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

You can use func_get_args(), it will return an array of arguments.

function work_with_arguments() {
    echo implode(", ", func_get_args());
}

work_with_arguments("Hello", "World");
//Outputs: Hello, World

Calling func_get_args() inside of your function will return an array of the arguments passed to PHP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!