Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure::bindTo how it's work?

Tags:

closures

oop

php

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:

  1. When we write in the line marked 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"?
  2. If instead of "A" write, "static" in the context of an anonymous function which will be executed?
  3. If we write in the second argument "static", then is it something associated with the LSB?
like image 207
MaximPro Avatar asked Oct 05 '16 21:10

MaximPro


1 Answers

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
like image 162
bwoebi Avatar answered Nov 09 '22 15:11

bwoebi