Overloading Functions In PHP

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

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

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<$intArgs; ++$i ) {
  $current = func_get_arg($i);
  // do something with argument

Add new comment

The content of this field is kept private and will not be shown publicly.
2 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.