Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the good example of using 'func_get_arg' in PHP?

Tags:

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?

like image 852
user482594 Avatar asked Mar 11 '11 01:03

user482594


People also ask

What is func_ get_ args()?

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.

How do you get the number of arguments passed to a PHP function?

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.

Which of the following function returns an array of all parameters provided to function?

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.


2 Answers

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.

like image 169
alex Avatar answered Sep 19 '22 18:09

alex


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); 
like image 27
Jon Avatar answered Sep 21 '22 18:09

Jon