Detailed explanation of the use of PHP variable functions
- 2020-06-12 08:46:50
- OfStack
PHP supports the concept of mutable functions. This means that if a variable name has parentheses after it, PHP will look for a function with the same name as the value of the variable and try to execute it. Variable functions can be used to achieve a number of purposes including callback functions, function tables.
Variable functions cannot be used in language constructs such as echo(), print(), unset(), isset(), empty(), include(), require(), and similar statements. You need to use your own wrapper functions to use these structures as variable functions.
Example of Example #1 variable function
Example #2 Variable method example
Variable functions cannot be used in language constructs such as echo(), print(), unset(), isset(), empty(), include(), require(), and similar statements. You need to use your own wrapper functions to use these structures as variable functions.
Example of Example #1 variable function
<?php
function foo () {
echo "In foo()<br />/n" ;
}
function bar ( $arg = '' ) {
echo "In bar(); argument was ' $arg '.<br />/n" ;
}
// use echo Wrapper function of
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()
?>
You can also take advantage of the nature of mutable functions 1 Method of an object.
Example #2 Variable method example
<?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()
?>