PHP可变函数的使用详解
更新时间:2013年06月14日 16:14:49 作者:
本篇文章是对PHP中可变函数的使用进行了详细的分析介绍,需要的朋友参考下
PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。
变量函数不能用于语言结构,例如 echo() ,print() ,unset() ,isset() ,empty() ,include() ,require() 以及类似的语句。需要使用自己的包装函数来将这些结构用作变量函数。
Example #1 可变函数示例
<?php
function foo () {
echo "In foo()<br />/n" ;
}
function bar ( $arg = '' ) {
echo "In bar(); argument was ' $arg '.<br />/n" ;
}
// 使用 echo 的包装函数
function echoit ( $string )
{
echo $string ;
}
$func = 'foo' ;
$func (); // This calls foo()
$func = 'bar' ;
$func ( 'test' ); // This calls bar()
$func = 'echoit' ;
$func ( 'test' ); // This calls echoit()
?>
还可以利用可变函数的特性来调用一个对象的方法。
Example #2 可变方法范例
<?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()
?>
变量函数不能用于语言结构,例如 echo() ,print() ,unset() ,isset() ,empty() ,include() ,require() 以及类似的语句。需要使用自己的包装函数来将这些结构用作变量函数。
Example #1 可变函数示例
复制代码 代码如下:
<?php
function foo () {
echo "In foo()<br />/n" ;
}
function bar ( $arg = '' ) {
echo "In bar(); argument was ' $arg '.<br />/n" ;
}
// 使用 echo 的包装函数
function echoit ( $string )
{
echo $string ;
}
$func = 'foo' ;
$func (); // This calls foo()
$func = 'bar' ;
$func ( 'test' ); // This calls bar()
$func = 'echoit' ;
$func ( 'test' ); // This calls echoit()
?>
还可以利用可变函数的特性来调用一个对象的方法。
Example #2 可变方法范例
复制代码 代码如下:
<?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()
?>
相关文章
提示Trying to clone an uncloneable object of class Imagic的解决
使用网上流传的一个程序实现pdf截图为png,需要使用Imagic扩展,安装后出现Trying to clone an uncloneable object of class Imagic提示,下面是具体的解决方法分享。2011-10-10
Php output buffering缓存及程序缓存深入解析
在php中有时为了控制程序的输出显示顺序,提供了output buffering缓存(php自身缓存机制)。若Ob缓存开启,需要输出的就先存在ob缓存里,再到程序缓存里。若没有开启,则直接进入程序缓存,程序执行完毕,按照顺序从程序缓存里输出2013-07-07
PHP中通过ADODB库实现调用Access数据库之修正版本
PHP中通过ADODB库实现调用Access数据库之修正版本...2006-12-12


最新评论