PHP 支援可變函數的概念。這意味著如果一個變數名後有圓括弧,PHP 將尋找與變數的值同名的函數,並且嘗試執行它。可變函數可以用來實現包括回呼函數,函數表在內的一些用途。
可變函數不能用於例如 echo , print , unset() , isset() , empty() , include , require 以及類似的語言結構。需要使用自己的封裝函數來將這些結構用作可變函數。
Example #1 可變函數樣本
<?phpfunction 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 可變方法範例
<?phpclass 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()?>
當調用靜態方法時,函數調用要比靜態屬性優先:
Example #3 Variable 方法和靜態屬性樣本
<?phpclass Foo{ static $variable = 'static property' ; static function Variable () { echo 'Method Variable called' ; }}echo Foo :: $variable ; // This prints 'static property'. It does need a $variable in this scope.$variable = "Variable" ;Foo :: $variable (); // This calls $foo->Variable() reading $variable in this scope.?>