Detailed explanation of the use of PHP variable functions_PHP tutorial

WBOY
Release: 2016-07-21 15:06:32
Original
775 people have browsed it

PHP supports the concept of variadic functions. This means that if there are parentheses after a variable name, 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

Copy code The code is as follows:

function foo () {
echo "In foo()
/n" ;
}
function bar ( $arg = '' ) {
echo "In bar(); argument was ' $arg '.
/n" ;
}
// Use the wrapper function of 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 methods of an object.

Example #2 Variable method example
Copy code The code is as follows :

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()
?> ;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327615.htmlTechArticlePHP supports the concept of variable functions. This means that if there are parentheses after a variable name, 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...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template