Tuesday, 5 March 2013

PHP function with a variable number of arguments

Introduction

If you have ever needed to make a function in PHP and have it accept any number of arguments (rather than a fixed number) then this is the post you've been looking for.

Now I should point out this is probably bad coding practise and you should structure your functions as methods in a class with clearly defined roles within the class so they don't need to accept a varying number of arguments. Really what you should be doing is re-thinking the way that class is working / architected, this isn't always possible though due to business / time constraints and working with someone else's code which is why I've written this post.

The code

function foo(){
    $args = func_get_args();

    var_dump($args);
}

foo('bar');

Code Explanation

This block of code is pretty simple, there is a defined function which doesn't have any parameters set and inside of it the func_get_args (a pre-defined PHP function) is called which gets all the arguments passed to this function and puts them as an array in the $args variable. All of these arguments are then displayed to the screen using var_dump.

This function is called and has the argument "bar" passed to it which will be displayed to the screen with var_dump despite the function having no defined parameters.

That's it. Remember you should avoid using this but if you ever really need to use it, that's how.