Method Example of Dynamic Obtaining Function Parameters by PHP

  • 2021-09-16 06:25:44
  • OfStack

In this paper, an example is given to describe the method of dynamically obtaining function parameters by PHP. Share it for your reference, as follows:

PHP supports a variable number of parameter lists in user-defined functions. In fact, it is very simple, just use func_num_args() , func_get_arg() , and func_get_args() Function will do.

Variable arguments do not require special syntax, and the argument list is still passed to the function as defined by the function, and these arguments are used in the usual way.

1. func_num_args-Returns the total number of arguments passed into the function

int func_num_args ( void )

Example


<?php
function demo ()
{
  $numargs = func_num_args ();
  echo " The number of parameters is : $numargs \n" ;
}
demo ( 'a' , 'b' , 'c' );

Running result

Number of parameters: 3

2. func_get_args-Returns the argument list of the passed-in function

array func_get_args  ( void )

Example


<?php
function demo ()
{
  $args = func_get_args();
  echo " The parameters passed in are :";
  var_dump($args);
}
demo ( 'a' , 'b' , 'c' );

Running result

The parameters passed in are:
array (size=3)
0 = > string 'a' (length=1)
1 = > string 'b' (length=1)
2 = > string 'c' (length=1)

3. func_get_arg-Returns parameter values from the parameter list based on the parameter index

mixed  func_get_arg  ( int $arg_num  )

Example


<?php
function demo ()
{
  $numargs = func_num_args ();
  echo " The number of parameters is : $numargs <br />" ;
  $args = func_get_args();
  if ( $numargs >= 2 ) {
    echo " No. 1 2 Parameters are : " . func_get_arg ( 1 ) . "<br />" ;
  }
}
demo ( 'a' , 'b' , 'c' );

Running result

Number of parameters: 3
The second parameter is: b

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Tutorial on Data Structure and Algorithms of PHP", "Summary of Programming Algorithms of php" and "Complete Collection of Operation Skills of PHP Array (Array)"

I hope this article is helpful to everyone's PHP programming.


Related articles: