可變函數
PHP 支援可變函數的概念。這意味着如果一個變量名後有圓括号,PHP
将尋找與變量的值同名的函數,并且嘗試執行它。可變函數可以用來實作包括回調函數,函數表在内的一些用途。
可變函數不能用于例如
[echo](php7/function.echo),[print](php7/function.print),[unset()](php7/function.unset),[isset()](php7/function.isset),[empty()](php7/function.empty),[include](php7/function.include),[require](php7/function.require)
以及類似的語言結構。需要使用自己的包裝函數來将這些結構用作可變函數。
Example #1 可變函數示例
function foo() {
echo "In foo()
\n";
}
function bar($arg = '') {
echo "In bar(); argument was '$arg'.
\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 可變方法範例
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()
?>
當調用靜态方法時,函數調用要比靜态屬性優先:
Example #3 Variable 方法和靜态屬性示例
class 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.
?>
As of PHP 5.4.0, you can call any [callable](php7/language.types.callable) stored in a variable.
Example #4 Complex callables
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}
$func = array("Foo", "bar");
$func(); // prints "bar"
$func = array(new Foo, "baz");
$func(); // prints "baz"
$func = "Foo::bar";
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
?>
參見 [is_callable()](php7/function.is-callable),[call_user_func()](php7/function.call-user-func),[可變變量](php7/language.variables.variable)和
[function_exists()](php7/function.function-exists)。
更新日志
版本
說明
7.0.0
'ClassName::methodName' is allowed as variable function.
5.4.0
Arrays, which are valid callables, are allowed as variable functions.