I just have found out that there is a function called func_get_arg
in PHP which enables developer to use variant style of getting arguments. It seems to be very useful because number of argument can now be arbitrary, but I cannot think of any good example of using it.
What are the some examples of using this function to fully benefit its polymorphic characteristic?
The func_get_args() function can return an array in which each element is a corresponding member of the current user-defined function's argument list. This function can generate a warning if called from outside of function definition.
To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you.
func_get_args( ) returns an array of all parameters provided to the function, func_num_args( ) returns the number of parameters provided to the function, and func_get_arg( ) returns a specific argument from the parameters.
I usually use func_get_args()
which is easier to use if wanting multiple arguments.
For example, to recreate PHP's max()
.
function max() { $max = -PHP_INT_MAX; foreach(func_get_args() as $arg) { if ($arg > $max) { $max = $arg; } } return $max; }
CodePad.
Now you can do echo max(1,5,7,3)
and get 7
.
First of all, you are using the term "polymorphism" totally wrong. Polymorphism is a concept in object-oriented programming, and it has nothing to do with variable number of arguments in functions.
In my experience, all func_get_args
allows you to do is add a little syntactic sugar.
Think of a function that can take any number of integers and return their sum. (I 'm cheating, as this already exists in array_sum
. But cheating is good if it keeps the example simple). You could do it this way:
// you can leave "array" out; I have it because we should be getting one here function sum1(array $integers) { return array_sum($integers); }
Now you would call this like so:
$sum = sum1(array(1)); $sum = sum1(array(1, 2, 3, 4));
This isn't very pretty. But we can do better:
function sum2() { $integers = func_get_args(); return array_sum($integers); }
Now you can call it like this:
$sum = sum2(1); $sum = sum2(1, 2, 3, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With