php中的变量函数
php中的变量函数,是个容易被忽视的用法,笔记下如果一个变量名后面有括号,PHP将寻找与该变量值同名的函数,并且尝试执行它.PHP“可变函数”可以用来实现包括回调函数、函数表在内的一些用途.
“可变函数”不能用于语言结构,如 echo(),print(),unset(),iset(),empty(),include(),rquire()等,需要使用自定义的包装函数来将这些结构用作变量函数.
例如:
function echoString($str){
echo($str);
}
$varFun = “echoString”;
$varFun(“Output String”); // 输出”Output String”.
又如:
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test');// This calls bar()
$func = 'echoit';
$func('test');
<?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()
?>
页:
[1]