Home  >  Article  >  Backend Development  >  Some usage examples of php anonymous functions

Some usage examples of php anonymous functions

怪我咯
怪我咯Original
2017-06-28 11:55:581227browse

Anonymous functions (Anonymous functions), also called closure functions, allow temporarily creating a function without a specified name. The value most often used as the callback function (callback) parameter. Of course, there are other applications as well.

Example #1 Anonymous function example

<?php
echo  preg_replace_callback ( &#39;~-([a-z])~&#39; , function ( $match ) {
    return  strtoupper ( $match [ 1 ]);
},  &#39;hello-world&#39; );
// 输出 helloWorld
?>

Closure functions can also be used as the value of variables. PHP will automatically convert this expression into an object instance of the built-in class Closure. The method of assigning a closure object to a variable is the same as the syntax of ordinary variable assignment. A semicolon must be added at the end:

Example #2 Example of anonymous function variable assignment

<?php
$greet  = function( $name )
{
     printf ( "Hello %s\r\n" ,  $name );
};

$greet ( &#39;World&#39; );
$greet ( &#39;PHP&#39; );
?>

closure Packages can inherit variables from the parent scope. Any such variables should be passed in using the use language construct.

Example #3 Inherit variables from the parent scope

<?php
$message  =  &#39;hello&#39; ;

// 没有 "use"
$example  = function () {
     var_dump ( $message );
};
echo  $example ();

// 继承 $message
$example  = function () use ( $message ) {
     var_dump ( $message );
};
echo  $example ();

// Inherited variable&#39;s value is from when the function
// is defined, not when called
$message  =  &#39;world&#39; ;
echo  $example ();

// Reset message
$message  =  &#39;hello&#39; ;

// Inherit by-reference
$example  = function () use (& $message ) {
     var_dump ( $message );
};
echo  $example ();

// The changed value in the parent scope
// is reflected inside the function call
$message  =  &#39;world&#39; ;
echo  $example ();

// Closures can also accept regular arguments
$example  = function ( $arg ) use ( $message ) {
     var_dump ( $arg  .  &#39; &#39;  .  $message );
};
$example ( "hello" );
?>

The output of the above routine is similar to:

Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"

These variables must be declared at the head of the function or class. Inheriting variables from the parent scope is different from using global variables. Global variables exist in a global scope, no matter which function is currently executing. The parent scope of a closure is the function that defines the closure (not necessarily the function that calls it). Examples are as follows:

Example #4 Closures and Scope

<?php
// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
// 其中有一个方法用来计算购物车中所有商品的总价格,该方法使
// 用了一个 closure 作为回调函数。
class  Cart
{
    const  PRICE_BUTTER   =  1.00 ;
    const  PRICE_MILK     =  3.00 ;
    const  PRICE_EGGS     =  6.95 ;

    protected    $products  = array();
    
    public function  add ( $product ,  $quantity )
    {
         $this -> products [ $product ] =  $quantity ;
    }
    
    public function  getQuantity ( $product )
    {
        return isset( $this -> products [ $product ]) ?  $this -> products [ $product ] :
                FALSE ;
    }
    
    public function  getTotal ( $tax )
    {
         $total  =  0.00 ;
        
         $callback  =
            function ( $quantity ,  $product ) use ( $tax , & $total )
            {
                 $pricePerItem  =  constant ( CLASS  .  "::PRICE_"  .
                     strtoupper ( $product ));
                 $total  += ( $pricePerItem  *  $quantity ) * ( $tax  +  1.0 );
            };
        
         array_walk ( $this -> products ,  $callback );
        return  round ( $total ,  2 );;
    }
}

$my_cart  = new  Cart ;

// 往购物车里添加条目
$my_cart -> add ( &#39;butter&#39; ,  1 );
$my_cart -> add ( &#39;milk&#39; ,  3 );
$my_cart -> add ( &#39;eggs&#39; ,  6 );

// 打出出总价格,其中有 5% 的销售税.
print  $my_cart -> getTotal ( 0.05 ) .  "\n" ;
// 最后结果是 54.29
?>

Anonymous functions are currently implemented through the Closure class.


Version Description


5.4.0 $this can be used for anonymous functions.

5.3.0 Anonymous functions can be used.


The above is the detailed content of Some usage examples of php anonymous 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