首頁  >  文章  >  後端開發  >  php任意参数数目的函数

php任意参数数目的函数

WBOY
WBOY原創
2016-07-25 08:52:04965瀏覽
  1. // function with 2 optional arguments

  2. function foo($arg1 = '', $arg2 = '') {
  3. echo "arg1: $arg1\n";

  4. echo "arg2: $arg2\n";
  5. }

  6. foo('hello','world');

  7. /* prints:
  8. arg1: hello
  9. arg2: world
  10. */
  11. foo();

  12. /* prints:
  13. arg1:
  14. arg2:
  15. */
复制代码

如何建立能够接受任何参数数目的函数。 需要使用 func_get_args() 函数:

  1. // yes, the argument list can be empty

  2. function foo() {
  3. // returns an array of all passed arguments

  4. $args = func_get_args();
  5. foreach ($args as $k => $v) {

  6. echo "arg".($k+1).": $v\n";
  7. }
  8. }

  9. foo();

  10. /* prints nothing */
  11. foo('hello');

  12. /* prints
  13. arg1: hello
  14. */
  15. foo('hello', 'world', 'again');

  16. /* prints
  17. arg1: hello
  18. arg2: world
  19. arg3: again
  20. */
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn