For example, i have some code:
class A
{
private $value = 100;
}
$a = new A;
$closure = function(){echo $this->value;};
$binding = $closure->bindTo($a,"A"); /// tag
$binding();
I have some questions:
tag
second argument as an "A", does it mean that the execution context is inside an anonymous function is the same as inside the class "A"?Let me help you interpret the manual at http://php.net/Closure.bindTo
newscope
The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.
So, to answer your first question, yes, it means the code is interpreted like it were a method of the A
class.
If the context were "static"
(second question), then, when executing you get:
Fatal error: Cannot access private property A::$value in php shell code on line 1
That's because "static"
will keep the current [scope] (i.e. the scope which the Closure has been set to last; e.g. if it's bound to A
, it will remain bound to A
). In this case, it was simply unscoped and now still is unscoped; it doesn't magically behave like it were part of A
class (or any of the classes extending it) and thus does not have access to the protected or private properties.
Regarding the third question, "static"
here is just preserving the currently set scope. It has no further meaning. The only reason for "static"
as identifier is that no class may be named static
(thus it won't clash with any possible class name).
I.e. (using $closure
from your initial example):
$binding = $closure->bindTo($a, "A"); // scope is now A class
$second_binding = $binding->bindTo($a, "static"); // scope is still A class
$second_binding(); // works fine, no access issues
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With