Accessing private properties/methods using Closure - 19 Nov 2013

Closure

Closure, also known as anonymous function became available in PHP5.3 .

Anonymous functions are implemented using the Closure class.

$closure = function () {};

var_dump($closure instanceof \Closure); // bool(true);

Closure::bindTo in PHP5.4

In PHP5.4, $this can be used in anonymous functions. And also, closure rebinding is supported.

PHP: Closure::bindTo - http://php.net/manual/en/closure.bindto.php

public Closure Closure::bindTo ( object $newthis [, mixed $newscope = 'static' ] )

newthis

The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.

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.

Accessing private properties/methods

For example, following class A has just one private property, and no getter/setter methods.

class A
{
    private $a = 'secret';
}

Off course, you can't access property $a directly.

$a = new A();
echo $a->a;

Following example works as expected.

$accessor = function () {
    return $this->a;
};
$accessor = $accessor->bindTo($a, $a);

echo $accessor();

$accessor->bindTo($a, $a); creates new closure instance. First argument changes the value of $this, and second one changes the scope to class A.

comments powered by Disqus