Home > Article > Backend Development > What are the uses of PHP variable functions? Detailed examples
PHP supports the concept of variable functions. This means that if a variable name has parentheses after it, PHP will look for a function with the same name as the variable's value and try to execute it. Variable functions can be used to implement some purposes including callback functions and function tables.
Variable functions cannot be used in language structures, such as echo(), print(), unset(), isset(), empty(), include() , require() and similar statements . You need to use your own wrapper function to use these structures as variable functions.
Example #1 Variable function example
The code is as follows:
<?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() ?>
You can also use the characteristics of variable functions to Call a object method.
Example #2 Variable method example
The code is as follows:
<?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() ?>
The above is the detailed content of What are the uses of PHP variable functions? Detailed examples. For more information, please follow other related articles on the PHP Chinese website!