php closure usage example

1. Implement 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 added, 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();
 
// The closure is used here, so the User class is not actually instantiated. It will only be instantiated when get later 
$di ->set('a', function (){
     return  new User(' Zhang three' );
});
 
var_dump($di->get('a')->getUserName());

2. Use 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__ . '::PRICE_' . 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);

3. Use the closure function to call the method in the class

class Grid
{
    protected $builder;
    protected $attribute;
 
    public function __construct(Closure $builler)
    {
        $this->builder = $builler;
    }
 
    public function addColumn($name, $value)
    {
        $this->attribute[$name] = $value;
        return $this;
    }
 
    public function build()
    {
        // The callback closure function here, the 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 = new Grid(
     // Incoming closure function with parameters 
    function ( $grid ) {
         $grid ->addColumn('key1', 'val1' );
         $grid ->addColumn('key2', 'val2' );
    }
);
 
echo $grid;

 

 

 

 

Related articles: http://www.cnblogs.com/fps2tao/p/8727482.html

 

Transfer: https://www.cnblogs.com/itfenqing/p/7073307.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324511952&siteId=291194637