I have been blissfully unaware of the php function func_get_args()
, and now that I have discovered it I want to use it everywhere. Are there any limitations of using func_get_args
as compared to explicit argument declaration in the function definition?
You shouldn't use func_get_args
unless you actually need it.
If you define a function to take a specific number of arguments, PHP will raise an error if you don't supply enough arguments at call time.
If you take any number of arguments via func_get_args
, it's up to you to specifically check that all the arguments you're expecting have been passed to your function.
Similarly, you lose the ability to use type hinting, you can't supply default values, and it becomes much harder to tell what arguments your function expects at a glance.
In short, you prevent PHP from helping you catch (potentially difficult to debug) logic errors.
function do_stuff(MyClass tmpValue, array $values, $optional = null) {
// This is vastly better...
}
function do_stuff() {
// ... than this
}
Even if you want to allow a variable number of arguments, you should explicitly specify as many arguments as you can:
/**
* Add some numbers
* Takes two or more numbers to add together
*/
function add_numbers($num_1, $num_2 /* ..., $num_N */) {
$total = 0;
for ($i = 0; $i < func_num_args(); ++$i)
$total += func_get_arg($i);
return $total;
}
add_numbers(1,2); // OK!
add_numbers(1,2,3); // OK!
add_numbers(1) // Error!
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