PHP可变函数的使用详解

yipeiwu_com6年前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()
?>

相关文章

PHP标准库(PHP SPL)详解

PHP标准库(PHP SPL)详解

什么是SPL? SPL,PHP 标准库(Standard PHP Library) ,此从 PHP 5.0 起内置的组件和接口,并且从 PHP5.3 已逐渐的成熟。SPL 其实在所有的...

php header功能的使用

header() 函数向客户端发送原始的 HTTP 报头。复制代码 代码如下:<?php//200 正常状态header('HTTP/1.1 200 OK');// 301 永久重...

POSIX 风格和兼容 Perl 风格两种正则表达式主要函数的类比(preg_match, preg_replace, ereg, ereg_replace)

首先来看看 POSIX 风格正则表达式的两个主要函数: ereg 函数:(正则表达式匹配) 格式:int ereg ( string pattern, string string [,...

PHP设置Cookie的HTTPONLY属性方法

httponly是微软对cookie做的扩展,这个主要是解决用户的cookie可能被盗用的问题。 大家都知道,当我们去邮箱或者论坛登陆后,服务器会写一些cookie到我们的浏览器,当下次...

php简单浏览目录内容的实现代码

如下所示:复制代码 代码如下:<?php$dir = dirname(__FILE__);$open_dir = opendir($dir);echo "<table bor...