-
-
// function with 2 optional arguments
- function foo($arg1 = '', $arg2 = '') {
echo "arg1: $arg1n ";
- echo "arg2: $arg2n";
}
foo('hello','world');
- /* prints:
- arg1 : hello
- arg2: world
- */
foo();
- /* prints:
- arg1:
- arg2:
- */
-
Copy code
How to create a function that accepts any number of arguments.
You need to use the func_get_args() function:
-
-
// yes, the argument list can be empty
- function foo() {
// returns an array of all passed arguments
- $args = func_get_args();
foreach ($args as $k => $v) {
- echo "arg".($k+1).": $vn";
- }< ;/p>
}
foo();
- /* prints nothing */
foo('hello');
- / * prints
- arg1: hello
- */
foo('hello', 'world', 'again');
- /* prints
- arg1: hello
- arg2: world
- arg3: again
- */
-
Copy code
|