PHP 支持变量函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且将尝试执行它。除了别的事情以外,这个可以被用于实现回调函数,函数表等等。
变量函数不能用于语言结构,例如 echo(),print(),unset(),isset(),empty(),include(),require() 以及类似的语句。需要使用自己的外壳函数来将这些结构用作变量函数。
<?php
function foo() {
}
function bar($arg = '') {
}
// This is a wrapper function around echo
function echoit($string)
{
}
$func = 'foo';
$func();
$func = 'bar';
$func('test');
$func = 'echoit';
$func('test');
?>
输出结果:In foo()
In bar(); argument was 'test'.
test
<?php
class Foo
{
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();
?>
输出结果:This is Bar