Question: PHP - Encapsulation when referenced in function scope


PHP - Encapsulation when referenced in function scope

Answers 1
Added at 2017-01-03 07:01

I was going through the PHP 7.0 changes and came across Closure Call. The code in the documentation is the following.

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 is the line after the first comment able to return the x value? Does this not break encapsulation?

It seems like when x is referenced inside the function closure we are actually in class scope for some reason.

Answers to

PHP - Encapsulation when referenced in function scope

nr: #1 dodano: 2017-01-03 07:01

Indeed the new function that is created with bindTo sets the scope of that new function to A. This is as described in the documentation on bindTo:

Create and return a new anonymous function with the same body and bound variables as this one, but possibly with a different bound object and a new class scope.

The “bound object” determines the value $this will have in the function body and the “class scope” represents a class which determines which private and protected members the anonymous function will be able to access. Namely, the members that will be visible are the same as if the anonymous function were a method of the class given as value of the newscope parameter.

Note the last phrase " if...".

Source Show
◀ Wstecz