PHP supports the concept of variable functions. This means that if a variable name is followed by parentheses, 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 implement some uses including callback functions, function tables, and so on.
Variable functions cannot be used for example Echo,print,unset (), Isset (), Empty (), Include,require, and similar language structures. You need to use your own wrapper functions to make these structures as variable functions.
Example #1 Variable Function Example <?php
function foo () {
echo "in foo () <br/>\n";
}
function bar ($arg = ') {
echo "in Bar" (); Argument was ' $arg '. <br/>\n ";
}
Wrapping functions that use 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 ()
?>
You can also invoke the method of an object using the syntax of a mutable function.
Example #2 Variable method paradigm <?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 ()
?>
When a static method is invoked, the function call takes precedence over the static property:
Example #3 Variable methods and Static Properties Example <?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.