This article describes the method of PHP to dynamically obtain function parameters. Share it for your reference, as follows:
PHP supports variable number of parameter lists in user-defined functions. It's actually very simple, just use itfunc_num_args()
, func_get_arg()
,andfunc_get_args()
function.
Variable parameters do not require special syntax, and the parameter list is still passed to the function as defined by the function, and these parameters are used in the usual way.
1. func_num_args — Returns the total number of parameters passed in 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 results
The number of parameters is: 3
2. func_get_args — Returns the parameter list of the incoming 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 results
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 — Return parameter value from parameter list based on 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 "The second parameter is: " . func_get_arg ( 1 ) . "<br />" ; } } demo ( 'a' , 'b' , 'c' );
Running results
The number of parameters is: 3
The second parameter is: b
For more information about PHP related content, please check out the topic of this site:Summary of common functions and techniques for php》、《Summary of usage of php strings》、《PHP data structure and algorithm tutorial》、《Summary of PHP Programming Algorithm"and"Complete collection of PHP array (Array) operation techniques》
I hope this article will be helpful to everyone's PHP programming.