Closure in PHP
Closure, an anonymous function, also known as anonymous functions, was introduced when php5.3. Anonymous functions are functions that do not have a name defined. This is a very memorable understanding of the definition of anonymous functions.
For example, the following code
function test() { return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure(test());print_r($a);exit;
The test () here will never be used as a testclosure parameter because it is not an "anonymous" function.
So it should be changed to this:
function () { return 100;};function testClosure(Closure $callback){ return $callback();}$a = testClosure($f);print_r($a);exit;
OK, what if you want to invoke an anonymous function inside a class?
ClassCpublic static function testc () { return function ($i) {return $i +100;}; }}< Span class= "Hljs-number" >function testclosure (Closure $callback) { Return $callback (13); $a = Testclosure (C::TESTC ());p rint_r ($a); exit;
This should be the case, where C::TESTC () returns a Funciton.
The concept of binding
The above example of closure is just a global anonymous function, OK, I now want to specify a class that has an anonymous function. It can also be understood that the access scope of this anonymous function is no longer global, and is the access scope of a class.
Then we need to bind an anonymous function to a class.
<?phpclass A {public $base = 100;} class B { private $base = 1000;} $f = function () { return $this->base + 3;}; $a = Closure::bind ($f, new A);p Rint_r ($a ()); echo php_eol; $b = Closure::bind ($f, new B, ' B ');//The last parameter shows the function of the binding anonymous function is: public or Protectprint_r ($b ()); echo php_eol;
In the example above,ThisAPunicNameLetterNumberIn mo name Odd wonderful F This anonymous function has a strange and wonderful one, this keyword is to show that this anonymous function needs to be bound in the class.
After binding, it is as if there is such a function in a, but the function is public or the last parameter of Private,bind shows the callable scope of the function.
For BindTo, see example:
<?phpClassAPublic $base =100;}ClassBPrivate $base =1000;}ClassCPrivatestatic $base =10000;} $f =function () {return $this Base + 3;}; $SF = static function () {return self:: $base + 3;}; $a = Closure::bind ($f, new a);p Rint_r ($a ()); new B, echo php_eol; $c = $sf->bindto (null, ' C ');p Rint_r ($c ()); echo php_eol;
from:https://www.cnblogs.com/yjf512/p/4421289.html
Closure in PHP