[Webinar] Streamline your web hosting managementRegister Today

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 365

# anonymous function, closure

from example #3
http://www.php.net/manual/en/functions.anonymous.php

``````<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
const PRICE_BUTTER  = 1.00;
const PRICE_MILK    = 3.00;
const PRICE_EGGS    = 6.95;

protected \$products = array();

{
\$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;

// Add some items to the cart

// Print the total with a 5% sales tax.
print \$my_cart->getTotal(0.05) . "\n";
// The result is 54.29
``````

I am having difficulty understanding code
and on call stack there is a cart->closure

0
rgb192
1 Solution

ConsultantCommented:
A closure is just an internal name for a more complex anonymous function. Think of a lambda as a very, very simple anonymous function that doesn't really have many moving parts inside of it (like a basic function that just adds a number or displays a value), while a closure is an anonymous function that has more functionality inside of it.

So to answer your question, the closure is just the special name for the anonymous function in that code example (the one assigned to \$callback).
0

Commented:
No points for this, please, but if you find yourself wondering where you can use an anonymous function, feel free to stop wondering and just define a named function or method.  You'll be in good company.  Some language constructs are solutions in search of a problem.
0

Author Commented:
Ray wrote no points.

I will move on to next code and not focus on anonymous.
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.