PHP函数call_user_func和call_user_func_array的使用
本文章介绍的call_user_func是PHP的内置函数,该函数允许用户调用直接写的函数并传入一定的参数,而call_user_func_array用一个数组作为参数调用一个回调函数 返回值为回调函数执行的结果或者为false,要传递参数给函数,作为一个索引数组。
call_user_func() 函数类似于一种特别的调用函数的方法,使用方法如下:
function test($a, $b) {
echo $a*$b;
}
call_user_func('test', 4, 5);
//---- echo 20 ----//函数第一个参数为用户自定义函数,第二个参数为自定义函数中的参数。
调用类内部的方法比较奇怪,居然用的是array,不知道开发者是如何考虑的,当然省去了new,也是满有新意的:
class test {
function demo($param) {
echo $param;
}
}
call_user_func(array("test", "demo"), "this is output result!");
//--- echo this is output result! ---//
call_user_func_array()函数和call_user_func()很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰:
function test($b, $c) {
echo $b;
echo $c;
}
call_user_func_array('test', array("a", "b"));
//------echo ab ---------//
call_user_func_array()函数也可以调用类内部的方法的
class class_demo {
function fun_demo($param1, $param2) {
echo $param1 + $param2;
}
}
call_user_func_array(array('class_demo', 'fun_demo'), array("1", "2"));//---- echo 3 -----//
这里只是说了函数的使用方法。具体的事例可以在网上找找。
<?php
function debug($var, $val)
{
echo "***DEBUGGINGnVARIABLE: $varnVALUE:";
if (is_array($val) || is_object($val) || is_resource($val)) {
print_r($val);
} else {
echo "n$valn";
}
echo "***n";
}
$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];
call_user_func_array('debug', array("host", $host));
call_user_func_array('debug', array("c", $c));
call_user_func_array('debug', array("_POST", $_POST));
?>教程链接:http://www.phprm.com/function/58997.html
随意转载~但请保留教程地址★