Since anonymous functions use objects of the Closure class, respectively, I have a question how and for what these objects can be used in particular the methods of this object.

  • _ _ Construct
  • bind
  • bindTo
  • call

The manual read, but did not understand the semantic load, but I would like to find out what was happening.

Addition

 1. bind(Closure $closure, object $newthis [,mixed $newscope = "static"]) 2. bindTo(object $newthis [,mixed $newscope = "static"]) 3. call(object $newthis [,mixed $... ]) 

The static method has 3 arguments, and the dynamic 2, it seems to me that everything is clear because the absence of the 3rd argument in the dynamic method is due to the fact that the Closure object is used when we use the bindTo method in the context of the object

Example 1:

 class A { private $value = 100; } $a = new A; $closure = function(){echo $this->value;}; $binding = $closure->bindTo($a,"A"); ///Если я не напишу "A" то интерпретатор ///выдаст ошибку, как работает второй аргумент, какая область видимости ///имеется ввиду когда я туда ничего не пишу ///(если ничего не указывать туда пропишется значение static, что подразумевается под этим значением) /// и что вообще возможно туда написать? ///Еще можно передать вместо объекта Null но у меня не получилось, как ///возможно это сделать? $binding(); /// Выдаст: 100 

Example 2:

 class A { private $value = 100; } $a = new A; $closure = function($arg1, $arg2){echo $this->value + $arg1 + $arg2;}; $closure->call($a, 50, 15); /// Выдаст 165 

Conclusion: There сall not many differences between bindTo and сall , well, I don’t see any difference, except that call is written shorter, but what’s the point? Why then bindTo ?

  • habrahabr.ru/post/186718 usage example - Alex
  • read, bypassing the private properties of the class object, but I saw it in the manual =) - MaximPro

1 answer 1

  1. His constructor is private. So you can forget about it and not remember.
  2. call - allows the closure to start in a specific scope. Applications mass. For example, you get from the server JSON, containing an array of geographic points, which is deserialized into this class:

     class Point{ private $lat; private $lon; private $description; private $type; } 

    Everything would be fine, but for further processing, you do not need separate $lat and $lon in Point , but you need the property of $coord , the class Coordinates , which will contain them and at the same time possess a bunch of useful methods (for example, give the distance from another point, the definition of the country etc.). Then we do that.

     $points = массив десериализованных объектов Point; $closure = function() { $this->coord = new Coord($this->lat, $this->lon);}; foreach ($points as $point){ $closure->call($point); } 
  3. bindTo, allows you to get a new closure, with an overdefined scope. (bind - the same, but statically). The application is about the same as that of call, but it gives the opportunity to postpone execution and operate a set of objects.

The difference between call () and bindTo () is that call () performs an anonymous function immediately, and bindTo () only binds the scope. Also, for call() object class will automatically be bindTo() , but not for bind() and bindTo() .

The difference between bind () and bindTo () is that bindTo () is a method of the instantiated Closure class, and bind () is its static method.

 <?php class Foo{ public $a = "a"; protected $b = "b"; private $c = "c"; } $obj= new Foo(); $cl = function(){echo $this->a, $this->b, $this->c, "\n";}; // выполнится сразу $cl->call($obj); // создаст новый объект Closure, привяжет его к объекту $obj и // выставит область видимости private и protected класс Foo $cl1 = $cl->bindTo($obj, "Foo"); // то-же самое, но статически $cl2 = Closure::bind($cl, $obj, "Foo"); // создаст новый Closure, привяжет к нему public объекта $obj, // private и protected же останутся текущими $cl3 = $cl->bindTo($obj); $cl1(); $cl2(); $cl3(); abc - $cl->call(); abc - $cl1(); abc - $cl2(); a<br /> - $cl3(); Обратите внимание, что public вывелся, а private и protected нет <b>Fatal error</b>: Uncaught Error: Cannot access protected property Foo::$b in [...][...]:10 Stack trace: #0 [...][...](20): Closure-&gt;{closure}() #1 {main} thrown in <b>[...][...]</b> on line <b>10</b><br /> 

Very simple words.

 bindTo(object $newthis [,mixed $newscope = "static"]) 

$ newthis - defines which object will be used when using the word $ this. $ newscope is a scope. It determines which objects of the class that have private and protected scope will be accessible in the closure.

For simplicity, just imagine (see the example above) that in the closure, $ obj was substituted instead of $ this everywhere. That is what the first argument answers.

With the second harder. It indicates the closure, in the context of which class the closure is executed. If it is not set, then the closure "thinks" that it runs exactly in the scope where it is running. Naturally, at the same time, private and protected fields and methods of the object $ obj will not be accessible to him.

If the second parameter is the class name (Foo), then the closure will think that it works inside the Foo class, that is, is its method. In this case, both private and protected will be available to him.

I really do not know how to explain it easier.

PS To instantiate a class is to create an instance of it. For example through the operator new .

  • Since I myself was trying to figure out what was happening, I understood the following: A constructor is needed in order not to produce objects through the new operator. bind is a static method and is called statically. bindTo - the dynamic method is called via the context of an object of the class Closure . call - remained for me incomprehensible because it is similar with bind and bindTo . PS I would like more explicit examples, and not just a description of what these methods are needed for - MaximPro
  • added a question - MaximPro
  • @MaximPro completed the answer - rjhdby
  • And in my example, where I ask what is static and what will this scope be? - MaximPro
  • From your example, $cl1 = $cl->bindTo($obj,"static"); What is this scope? - MaximPro