變量函數

PHP 支援變量函數的概念。這意味著若果一個變量名後有圓括號,PHP 將尋找與變量的值同名的函數,並且將嘗試執行它。除了別的事情以外,這個可以被用於實現回呼函數,函數表等等。

變量函數不能用於語系結構,例如 echo()print()unset()isset()empty()include()require() 以及類似的語句。需要使用自己的外殼函數來將這些結構用作變量函數。

例子 17-14. 變量函數示例

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

還可以利用變量函數的特性來呼叫一個對象的方法。

例子 17-15. 變量方法範例

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

?>

請參閱 call_user_func()可變變量function_exists()