可变函数
PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号, PHP 将寻找与变量的值同名的函数,并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。
<?php
/**
* Just a test function.
*
* @param void
* @return void
*/
function foo()
{
//
}
/**
* Just a test function.
*
* @param string $string
* @return void
*/
function bar(string $string)
{
//
}
$foo = 'foo';
$bar = 'bar';
$foo();
$bar('bar');
可以用可变函数的语法来调用一个对象的方法。
<?php
class Foo
{
/**
* Just a test method.
*
* @param void
* @return void
*/
public function method()
{
//
}
}
$foo = new Foo();
$method = 'method';
$foo->$method();
也可以用可变函数的语法来调用一个对象的静态属性和静态方法。
<?php
class Foo
{
/**
* Just a test property.
*
* @var string
*/
public static string $property = 'foo';
/**
* Just a test method.
*
* @param void
* @return string
*/
public static function method(): string
{
return 'bar';
}
}
$foo = 'property';
var_dump(Foo::$$foo); // string(3) "foo"
$foo = 'method';
var_dump(Foo::$foo()); // string(3) "bar"
还可以调用存储在变量中的任何可调用对象。
<?php
class Foo
{
/**
* Just a test method.
*
* @param void
* @return void
*/
public function method()
{
//
}
}
class Bar
{
/**
* Just a test method.
*
* @param void
* @return void
*/
public static function method()
{
//
}
}
$foo = [new Foo(), 'method'];
$foo();
$bar = ['Bar', 'method'];
$bar();
$bar = 'Bar::method';
$bar();
调用类中的 __invoke
魔术方法。
<?php
class Foo
{
/**
* This method is called when tries to call an object as a function.
*
* @param void
* @return void
*/
public function __invoke()
{
//
}
}
$foo = new Foo();
$foo();