Home  >  Article  >  类库下载  >  [Strengthening the PHP series] Shopping cart code explains PHP’s anonymous functions

[Strengthening the PHP series] Shopping cart code explains PHP’s anonymous functions

高洛峰
高洛峰Original
2016-10-09 12:46:441374browse

【Strengthening the PHP Series】Shopping Cart Code Description of PHP's Anonymous Functions

1. Definition: Anonymous functions (Anonymous functions), also called closures, allow temporary creation of a function without a specified name. The value most commonly used as a callback function argument. Of course, there are other applications as well.

2. Usage:

 1) As the value of a variable:

  The closure function can also be used as the value of a variable. 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

 2) Inherit variables from the parent scope:

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

 3) A complete example, illustrated with shopping cart code:

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

3. Reference:

 1) PHP official description of 'anonymous function': http://www.php.net/manual/zh /functions.anonymous.php

 2) The constant() function returns a constant value: http://www.runoob.com/php/func-misc-constant.html

 3) The array_walk() function returns a constant value in an array Apply a user-defined function to each element: http://www.w3school.com.cn/php/func_array_walk.asp

  4) The round() function rounds floating point numbers: http://www.w3school.com .cn/php/func_math_round.asp


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
Previous article:PHP variablesNext article:PHP variables

Related articles

See more