-
-
// function with 2 optional arguments
- function foo($arg1 = '', $arg2 = '') {
echo "arg1: $arg1\n";
- echo "arg2: $arg2\n";
}
foo('hello','world');
- /* prints:
- arg1: hello
- arg2: world
- */
foo();
- /* prints:
- arg1:
- arg2:
- */
-
复制代码
如何建立能够接受任何参数数目的函数。
需要使用 func_get_args() 函数:
-
-
// 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).": $v\n";
- }
}
foo();
- /* prints nothing */
foo('hello');
- /* prints
- arg1: hello
- */
foo('hello', 'world', 'again');
- /* prints
- arg1: hello
- arg2: world
- arg3: again
- */
-
复制代码
|