PHP closures bind and BindTo
The closure class is summarized as follows:
Closure { __construct ( void ) public static Closure bind (Closure $closure , object $newthis [, mixed $newscope = 'static'] public Closure bindTo (object $newthis [, mixed $newscope = 'static' ])}
Method Description:
Closure::__construct — 用于禁止实例化的构造函数Closure::bind — 复制一个闭包,绑定指定的$this对象和类作用域。Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。
An example of the bind method of a closed packet
<?php/** * Copy a closure that binds the specified $this object and class scope. * * @authorCrazy Old driver */classAnimal {Private Static $cat="Cat"; Private $dog="Dog"; Public $pig="Pig";}/* * Get animal class static Private member Properties */$cat=Static function(){returnAnimal::$cat;};/* * Get animal Instance Private member properties */$dog=function(){return $this->dog;};/* * Get animal Instance public member properties */$pig=function(){return $this->pig;};$bindCat=Closure:: Bind($cat, NULL, NewAnimal());//The scope of the animal instance is bound to the closure, but the $this object is not bound to the closure package$bindDog=Closure:: Bind($dog, NewAnimal(), ' Animal ');//Bind the scope of the animal class to the closure, and bind the animal instance object as a $this object to the closure$bindPig=Closure:: Bind($pig, NewAnimal());//Bind the animal instance object as a $this object to the closure, preserving the original scope of the closureEcho $bindCat(),' <br> ';//Based on binding rules, allow closures to get animal class static private member properties by scoped operatorEcho $bindDog(),' <br> ';////Based on binding rules, allow closures to get animal instance private member properties through the bound $this object (animal instance object)Echo $bindPig(),' <br> ';//Based on binding rules, allow closures to get animal instance public member properties through bound $this objects
Summarize:
- Bind function:
- Parameter 1 ($closure): Indicates a closure function
- Parameter 2 ($newthis): equivalent to the difference within/outside the function, the instance of the passed class is called internally, and Null is equivalent to calling it externally
- Parameter 3 ($newscope): equivalent to the class and instance invocation of the difference, the scope of the function, the transmission class represents the static invocation method, internal can be "class Name:: Property" In the way of Use; instance represents the way the instance is called, internal can be "-
Bind and BindTo of PHP closures