Home  >  Article  >  Backend Development  >  What is an anonymous function

What is an anonymous function

藏色散人
藏色散人Original
2019-01-22 09:23:2814109browse

Anonymous functions

Anonymous functions (Anonymous functions), also called closures, allow you to temporarily create a function without a specified name. The value most commonly used as a callback function argument. Of course, there are other applications as well.

What is an anonymous function

Anonymous functions are currently implemented through the Closure class.

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, and a semicolon must be added at the end:

Example of anonymous function variable assignment

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

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

Closures can inherit variables from the parent scope. Any such variables should be passed in using the use language construct. Starting from PHP 7.1, such variables cannot be passed in: superglobals, $this or have the same name as parameters.

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 at the head of the function or class Ministry statement. 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).

Closures and scope examples:

<?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
?>

This article is an introduction to anonymous functions. I hope it will be helpful to friends in need!

The above is the detailed content of What is an anonymous function. 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