Search code examples
phpargumentsfunction-declaration

Explicitly define the possibility of multiple unknown arguments in PHP


I want to create a function that may require multiple unknown arguments. I am currently not defining the argument list. The function definition looks like this

public static function SafeJoin()

and then I use $arguments_list = func_get_args(); inside the function to get the arguments into the list.

The problem with this approach is that there is no explicit way to know that the function can receive multiple arguments. Are there any approaches to the problem other than using an array as the explicit argument.


Solution

  • There is. But was added in PHP version 5.6.

    function myFunction(...$params)
    {
        echo '<pre>';
        print_r($params);
        echo '</pre>';
    }
    

    Inside function $params is simple array. You can call function with for example: myFunction(1,'foo',250,$bar);

    Click! for reference