Detailed explanation of PHP variable length parameter processing function

高洛峰
Release: 2023-03-06 06:28:01
Original
1504 people have browsed it

The example in this article describes the php variable length parameter processing function. Share it with everyone for your reference, the details are as follows:

Like C++, functions containing variable parameters can also be processed in PHP. The principle is the same, and a function is needed to specifically process the parameter list. PHP provides three related functions:

1. func_num_args() -- Returns the number of parameters passed to the function

int func_num_args ( void )

Example:

function open_database($DB, $cache_size_or_values=null, $cache_size=null)
{
  switch (function_num_args())
  {
    case 1:
      $r = select_db($DB);
      break;
    case 2:
      $r = select_db($DB, $cache_size_or_values);
      break;
    case 3:
      $r = select_db($DB, $cache_size_or_values, $cache_size);
      break;
  }
  return is_resource($r);
}
Copy after login

##2. func_get_arg() -- Return the specified parameter

mixed func_get_arg (int arg_num)

The arg_num of the first parameter in the parameter list is 0

<?php
  function some_func($a, $b)
  {
    for($i = 0; $i<func_num_args(); ++$i)
    {
      $param = func_get_arg($i);
      echo "the param is $param\n"
    }
  }
  some_func(1,3,5,7,9);
?>
Copy after login

3. func_get_args() -- Returns the parameter list in the form of an array

array func_get_args ( void )

Example:

<?php
  function some_other_func($a, $b)
  {
    $param = func_get_args();
    $param = join(", ", $param);  // 分解显示
    echo "the arglist is: $param\n";
  }
  some_other_func(1,3,5,7,9);
?>
Copy after login
For more detailed explanations of PHP variable-length parameter processing functions, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template