PHP - encapsulation on link in function area

I went through PHP 7.0 changes and came across Closing a call . The code in the documentation is as follows.

<?php class A {private $x = 1;} // Pre PHP 7 code $getXCB = function() {return $this->x;}; // this line $getX = $getXCB->bindTo(new A, 'A'); // intermediate closure echo $getX(); 

My question is: how can a line after the first comment return x? Doesn't that break encapsulation?

It seems that when x is mentioned inside the closure of the function, for some reason we are actually in the scope of the class.

+5
source share
1 answer

Indeed, a new function created using bindTo sets the scope of this new function to A This is described in the bindTo documentation :

Create and return a new anonymous function with the same bodies and related variables as this one, but possibly with another related object and a new scope of the class.

A “linked object” defines the value of $ that the function body will have, and a “scope class” represents a class that defines which private and protected members can access the anonymous function. Namely, the elements that will be visible are the same as if the anonymous function was a class method specified as the value of the newscope parameter.

Pay attention to the last phrase "... as if ...".

+3
source

Source: https://habr.com/ru/post/1262200/


All Articles