PHP 支锟街可变函锟斤拷锟侥革拷锟筋。锟斤拷锟斤拷味锟斤拷锟斤拷锟揭伙拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟皆诧拷锟斤拷牛锟絇HP 锟斤拷寻锟斤拷锟斤拷锟斤拷锟斤拷锟街低拷锟斤拷暮锟斤拷锟斤拷锟斤拷锟斤拷页锟斤拷锟街达拷锟斤拷锟斤拷锟斤拷杀浜拷锟斤拷锟斤拷锟斤拷锟斤拷锟绞碉拷职锟斤拷锟斤拷氐锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷诘锟揭恍╋拷锟酵撅拷锟�
锟缴变函锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 echo锟斤拷print锟斤拷unset()锟斤拷isset()锟斤拷empty()锟斤拷include锟斤拷require 锟皆硷拷锟斤拷锟狡碉拷锟斤拷锟皆结构锟斤拷锟斤拷要使锟斤拷锟皆硷拷锟侥帮拷装锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷些锟结构锟斤拷锟斤拷锟缴变函锟斤拷锟斤拷
Example #1 锟缴变函锟斤拷示锟斤拷
<?php
function 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 锟缴变方锟斤拷锟斤拷锟斤拷
<?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()
?>
锟斤拷锟斤拷锟矫撅拷态锟斤拷锟斤拷时锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷要锟饺撅拷态锟斤拷锟斤拷锟斤拷锟饺o拷
Example #3 Variable 锟斤拷锟斤拷锟酵撅拷态锟斤拷锟斤拷示锟斤拷
<?php
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 stored in a variable.
Example #4 Complex callables
<?php
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()锟斤拷call_user_func()锟斤拷锟缴憋拷锟斤拷锟�锟斤拷 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. |