>  기사  >  백엔드 개발  >  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으로 문의하세요.