Home  >  Article  >  Backend Development  >  Some examples about php variable functions

Some examples about php variable functions

怪我咯
怪我咯Original
2017-06-28 09:12:301117browse

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 with echo, print, unset(), isset(), empty(), include, require and similar language structures. Your own wrapper function is required to use these structures as variadic functions.

Example #1 Variable function example

<?php
function  foo () {
    echo  "In foo()<br />\n" ;
}

function  bar ( $arg  =  &#39;&#39; ) {
    echo  "In bar(); argument was &#39; $arg &#39;.<br />\n" ;
}

// 使用 echo 的包装函数
function  echoit ( $string )
{
    echo  $string ;
}

$func  =  &#39;foo&#39; ;
$func ();         // This calls foo()

$func  =  &#39;bar&#39; ;
$func ( &#39;test&#39; );   // This calls bar()

$func  =  &#39;echoit&#39; ;
$func ( &#39;test&#39; );   // This calls echoit()
?>

You can also use the syntax of variable function to call the method of an object.

Example #2 Variable method example

<?php
class  Foo
{
    function  Variable ()
    {
         $name  =  &#39;Bar&#39; ;
         $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 calling a static method, function calls take precedence over static properties:

Example #3 Variable Method and static property examples

<?php
class  Foo
{
    static  $variable  =  &#39;static property&#39; ;
    static function  Variable ()
    {
        echo  &#39;Method Variable called&#39; ;
    }
}

echo  Foo :: $variable ;  // This prints &#39;static property&#39;. It does need a $variable in this scope.
$variable  =  "Variable" ;
Foo :: $variable ();   // This calls $foo->Variable() reading $variable in this scope.

?>

The above is the detailed content of Some examples about php variable functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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