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双引号中访问数组元素报错的解决方法

最近在做微信公众号开发,在一个发送图文接口中,需要把数组元素拼接在XML字符串中 foreach ($itemArr as $key => $value){ $items...

PHP header()函数常用方法总结

//定义编码复制代码 代码如下:header( 'Content-Type:text/html;charset=utf-8 ');//Atom复制代码 代码如下:header('Cont...

PHP curl 抓取AJAX异步内容示例

PHP curl 抓取AJAX异步内容示例

其实抓ajax异步内容的页面和抓普通的页面区别不大。ajax只不过是做了一次异步的http请求,只要使用firebug类似的工具,找到请求的后端服务url和传值的参数,然后对该url传递...

PHP伪静态Rewrite设置之APACHE篇

 一、Apache配置:   1、支持httpd.conf 配置 2、支持目录 .htaccess配置(一种"分布式配置"文件针对虚拟空间,空间商不让修改Apache...

PHP CURL模拟登录新浪微博抓取页面内容 基于EaglePHP框架开发

复制代码 代码如下: /** * CURL请求 * @param String $url 请求地址 * @param Array $data 请求数据 */ function curlR...