Overloading Functions In PHP

16th July 2008 - 2 minutes read time

One thing that PHP doesn't allow is the creation of multiple functions with the same name. If you try this then PHP will give you a fatal error. Creating different functions with the same name is useful if you want to pass different parameters to a function that produces the same result. There are two ways around this problem.

The first is that you can pass the function an array of the items that you want. You can then use this array in the function to do whatever you want. For example.

function test($array)
{
 // do something with array
}
 
test(array(1,2,3,4));

The second involves the PHP functions to do with arguments. The main ones of interest here are func_num_args(), func_get_args() and func_get_arg(). This method allows you to send as many arguments as you want to your function and then get PHP to sort it out during the function execution. Here is the same function again, but constructed in a different way.

function test()
{
 $args = func_get_args();
// do something with arguments
}
 
test(1);
test(1,2,3,4,5,6,7,8,9);

The func_get_args() function will get all of the arguments sent to the function. An alternate method is provided by the func_get_arg() function. Used in conjunction with the func_num_args() function it is possible to iterate through the arguments quite easily.

function test()
{
 $intArgs = func_num_args();
 for ( $i=0; $i

Add new comment

The content of this field is kept private and will not be shown publicly.