Home > Article > Backend Development > Examples of func_num_args and func_get_args functions in php
This article introduces two functions related to variable function parameters in PHP, namely the func_num_args and func_get_args functions. Friends in need can refer to them.
First, let’s look at the func_num_args function. Function: Returns the number of parameters passed to the function Syntax: int func_num_args (void). Description: Returns the number of parameters passed to the currently defined function. func_get_arg() will generate a warning if this function is called from outside the function definition. func_num_args() can be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists. Among them, func_get_arg() returns items from the parameter list, its syntax: int func_get_arg (int arg_num), returns the arg_numth parameter of the parameter list that defines the function, and its parameters start from 0. And calling this function outside the function definition will generate a warning; and when arg_num is greater than the number of parameters actually passed by the function, a warning will also be generated and FALSE will be returned. Let’s look at the difference between the func_get_args() function and the func_get_arg() function: The func_get_args() function returns an array. Each element of the array is equivalent to the number of parameter columns of the current user-defined function. When building PHP classes, you can use these three functions flexibly to write better code. For example, when creating a class that links PHP and MYSQL, you can use the following method: <?php class mydb{ private $user; private $pass; private $host; private $db; public function __construct(){ $num_args=func_num_args(); if($num_args>0){ $args=func_get_args(); $this->host=$args[0]; $this->user=$args[1]; $this->pass=$args[2]; this->connect(); } } ?> |