::  ::  ::  ::  :: 管理

php 变量函数

Posted on 2008-06-07 22:00 nt05 阅读(207) 评论(0)  编辑 收藏 引用 所属分类: web

变量函数

PHP 支持变量函数的概念。这意味着如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数,并且将尝试执行它。除了别的事情以外,这个可以被用于实现回调函数,函数表等等。

变量函数不能用于语言结构,例如 echo()print()unset()isset()empty()include()require() 以及类似的语句。需要使用自己的外壳函数来将这些结构用作变量函数。

<?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' );   // This calls echoit()
?>

还可以利用变量函数的特性来调用一个对象的方法。

<?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()