php能把函数名作为参数传递吗

可以。方法主要介绍2种:
1.使用函数call_user_func()或者 call_user_func_array()
<?php
function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));
// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));

2.php本身是支持可变函数的,如同javascript一样:
例一:
function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}

$variable = 'bar';
foo($variable);

例二:
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // This calls the Bar() method
}

function Bar()
{
echo "This is Bar";
}
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()

?>
posted @ 2018-06-18 10:34  天涯海角路  阅读(1282)  评论(0)    收藏  举报