Detailed explanation of the usage of PHP functions call_user_func and call_user_func_array_PHP tutorial

WBOY
Release: 2016-07-13 10:36:57
Original
809 people have browsed it

The call_user_func function is used when a function needs to be dynamically called. This function has two uses:
The first is to call a lonely function:

Copy code The code is as follows:
function funa($b,$c)
{
echo $b;
echo $c;
}
call_user_func('funa', "111","222");
call_user_func('funa', "333","444");
//Display 111 222 333 444
//Have you noticed that this usage is a bit like the call method in javascript, hehe
?>

The second is to call the function inside the class:
Copy code The code is as follows:
class a {
function b()
{
$args = func_get_args( );
        $num = func_num_args(); ),"111","222");
?>

Run the above example yourself and see what the result is~ Hehe~ Please note that the func_get_args() function obtains the incoming The parameters in the function return an array, and the func_num_args() function obtains the number of parameters passed into the function.

Let’s take a look at the call_user_func_array function
This function is also used when a function needs to be called dynamically. Its usage is similar to the call_user_func function, except that the parameters are passed in as an array.

Copy code

The code is as follows:

function a($b, $c){ echo $b;
echo $c;
}
call_user_func_array('a', array("111", "222"));
//Display 111 222
? >


The call_user_func_array function can also call methods inside the class

Copy the code


The code is as follows:

Class ClassA{ function bc($b, $c) {
$bc = $b + $c;
echo $bc;
}

}

call_user_func_array(array('ClassA','bc'), array(“111″, “222″));
//Display 333
?>

Let’s look at another example of dynamically calling a function:


Copy the code

The code is as follows:
function otest1 ( $a){ echo( 'One parameter' );
}

function otest2 ( $a, $b)
{
echo( 'Two parameters ' );
}

function otest3 ( $a ,$b,$c)
{
echo( 'Three' );
}

function otest (){
$args = func_get_args();
$num = func_num_args();
call_user_func_array( 'otest'.$num, $args );
}
otest ("11");
otest("11","22");
otest("11","22","33");
?>





http://www.bkjia.com/PHPjc/736829.htmlwww.bkjia.com

truehttp: //www.bkjia.com/PHPjc/736829.htmlTechArticleThe call_user_func function is used when a function needs to be dynamically called. This function has two uses: The first It is a lonely function to be called: Copy the code as follows: ?php function fu...
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