I. Implementing a container based on closures
Class di{ private $factory; Public function set ($id, $value) { $this->factory[$id] = $value; } Public function Get ($id) { $val = $this->factory[$id]; return $val ();//If the parentheses are not enclosed, only the closure class is returned, not the User instance }}class user{ private $username; Public function __construct ($username = ") { $this->username = $username; } Public Function GetUserName () { return $this->username; }} $di = new Di ();//A closure is used here, so the User class is not actually instantiated, and the $di->set (' A ', function () { return new User (' Zhang San ') is instantiated only at the time of the back get;}); Var_dump ($di->get (' a ')->getusername ());
Two. Using closures as callbacks
Class cart{ CONST price_butter = 1.0; CONST price_milk = 5.05; protected $products = []; 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) { $priceItem = constant (__class__). '::P rice_ '. Strtoupper ($product)); $total + = ($priceItem * $quantity) * ($tax + 1.0); }; Array_walk ($this->products, $callback); Return round ($total, 2);} } $cart = new Cart (), $cart->add (' Butter ', 1), $cart->add (' Milk ', 5), Echo $cart->gettotal (0.05);
PHP Closure Use example