I. Implementing a container based on closures
classdi{Private $factory; Public functionSet$id,$value) { $this->factory[$id] =$value; } Public functionGet$id) { $val=$this->factory[$id]; return $val();//If you do not add parentheses, only the closure class is returned, not the user instance }} classuser{Private $username; Public function__construct ($username= ' ') { $this->username =$username; } Public functionGetUserName () {return $this-username; }} $di=NewDi ();//a closure is used here, so the user class is not actually instantiated and is instantiated only at the back of the Get$di->set (' A ',function(){ return NewUser (' Zhang San ');}); Var_dump($di->get (' a ')->getusername ());
Two. Using closures as callbacks
classcart{CONSTPrice_butter = 1.0; CONSTPrice_milk = 5.05; protected $products= []; Public functionAdd$product,$quantity) { $this->products[$product] =$quantity; } Public functionGetquantity ($product) { return isset($this->products[$product]) ?$this->products[$product]:false; } Public functionGettotal ($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=NewCart ();$cart->add (' Butter ', 1);$cart->add (' Milk ', 5); Echo $cart->gettotal (0.05);
Three. Calling a method in a class using a closure function
classgrid{protected $builder; protected $attribute; Public function__construct (Closure$builler) { $this->builder =$builler; } Public functionAddColumn ($name,$value) { $this->attribute[$name] =$value; return $this; } Public functionbuild () {//here callback closure function, parameter is this Call_user_func($this->builder,$this); } Public function__tostring () {$this-build (); $str= ' '; $call=function($val,$key) Use(&$str) { $str.= "$key=$val;"; }; Array_walk($this->attribute,$call); return $str; }} $grid=NewGrid (//incoming closure function with parameter function($grid) { $grid->addcolumn (' Key1 ', ' val1 '); $grid->addcolumn (' Key2 ', ' val2 '); }); Echo $grid;
Related article: http://www.cnblogs.com/fps2tao/p/8727482.html
Ext.: https://www.cnblogs.com/itfenqing/p/7073307.html
PHP Closure Use example