Chapter 26. Learning PHP Advanced Functions
In Chapter 5 we presented the basic features for user-defined functions in PHP. In this chapter, we move on to some exotic properties of functions, including ways to use variable numbers of arguments, ways to have functions actually modify the variables they are passed, and (cooler still) using functions as data.
Variable Numbers of Arguments
It's often useful to have the number of actual arguments that are passed to a function depend on the situation in which it is called. There are three possible ways to handle this in PHP:
Define the function with default arguments — any that are missing in the function call will have the default value, and no warning will be printed.
Use an array argument to hold the values — it is the responsibility of the calling code to package up the array, and the function body must appropriately take it apart.
Use the variable-argument functions (
func_num_args(), func_get_arg()
, andfunc_get_args()
).
The following sections address each of these possibilities.
Default arguments
To define a function with default arguments, simply turn the formal parameter name into an assignment expression. If the actual call has fewer parameters than the definition has formal parameters, PHP will match actual with formal until the actual parameters are exhausted and then will use the default assignments to fill in the ...
Get PHP6 and MySQL® 6 Bible now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.