PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。
变量函数不能用于语言结构,例如 echo() ,print() ,unset() ,isset() ,empty() ,include() ,require() 以及类似的语句。需要使用自己的包装函数来将这些结构用作变量函数。
Example #1 可变函数示例
<?php<BR>function foo () {<BR> echo "In foo()<br />/n" ;<BR>}<BR>function bar ( $arg = '' ) {<BR> echo "In bar(); argument was ' $arg '.<br />/n" ;<BR><div>)本文来源gaodai.ma#com搞#代!码网_</div><strong>搞代gaodaima码</strong>}<BR>// 使用 echo 的包装函数<BR>function echoit ( $string )<BR>{<BR> echo $string ;<BR>}<BR>$func = 'foo' ;<BR>$func (); // This calls foo()<BR>$func = 'bar' ;<BR>$func ( 'test' ); // This calls bar()<BR>$func = 'echoit' ;<BR>$func ( 'test' ); // This calls echoit()<BR>?> <BR>还可以利用可变函数的特性来调用一个对象的方法。 <BR>
Example #2 可变方法范例
<?php<BR>class Foo<BR>{<BR> function Variable ()<BR> {<BR> $name = 'Bar' ;<BR> $this -> $name (); // This calls the Bar() method<BR> }<BR> function Bar ()<BR> {<BR> echo "This is Bar" ;<BR> }<BR>}<BR>$foo = new Foo ();<BR>$funcname = "Variable" ;<BR>$foo -> $funcname (); // This calls $foo->Variable()<BR>?> <BR>