Home >Backend Development >PHP Tutorial >How to use bind() and bindTo() of PHP Closure class?
See the PHP manual for usage of Closure’s bind and bindTo. I really don't understand it and don't understand the concept.
For example, Closure::bind, the manual says "copy a closure and bind the specified $this object and class scope". How to understand this?
How are closures and $this bound together? What is class scope used for?
Also, one is a static version and the other is a dynamic version. What does this refer to?
Can you explain these concepts using the examples given?
<code><?php class A { private static $sfoo = 1; private $ifoo = 2; } $cl1 = static function() { return A::$sfoo; }; $cl2 = function() { return $this->ifoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); $bcl2 = Closure::bind($cl2, new A(), 'A'); echo $bcl1(), "\n"; echo $bcl2(), "\n"; ?></code>
Thank you
See the PHP manual for usage of Closure’s bind and bindTo. I really don't understand it and don't understand the concept.
For example, Closure::bind, the manual says "copy a closure and bind the specified $this object and class scope". How to understand this?
How are closures and $this bound together? What is class scope used for?
Also, one is a static version and the other is a dynamic version. What does this refer to?
Can you explain these concepts using the examples given?
<code><?php class A { private static $sfoo = 1; private $ifoo = 2; } $cl1 = static function() { return A::$sfoo; }; $cl2 = function() { return $this->ifoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); $bcl2 = Closure::bind($cl2, new A(), 'A'); echo $bcl1(), "\n"; echo $bcl2(), "\n"; ?></code>
Thank you
I don’t know if you have ever used call
or apply
in js
, which is somewhat similar.
In fact, the closure is treated as a member method or static member method of the object.
<code class="php">Closure::bind($cl1, null, 'A'); //就相当于在类里面加了个静态成员方法 Closure::bind($cl2, new A(), 'A'); //相当于在类里面加了个成员方法</code>
Member methods use $this
to access objects, and static member methods directly use classname::member
method.
But because it is an anonymous function and has no function name, it returns a bound $this object and class function. The closure of the domain is for you to use.