The public, protected and private access modifiers have been part of PHP since PHP5, allowing programmers to restrict access to class methods and properties according to their needs.
However in PHP there is a construct that circumvents these restrictions and allows the programmer to interact with methods and properties of an object irrespective of their accessibility modifiers, a tathagata-garbha where rules don't apply… where the merest inkling of desire allows access: this construct is the Closure.
To illustrate the capabilities of the closure I developed a class that I call PhpObjectDoctor (we often grant our doctor access to information that would otherwise be kept private).
First we need to be able to pass the PHP object that we want to interact with to the doctor:
Now we are ready to interact with the patient directly. To be able to do this we need to make use of PHPs magic methods:
To execute methods on the patient we use the magic __call method:
To set or get properties of the patient we use the magic __set and __get methods:
Now we can use the Object Doctor:
You might have noticed that the Object Doctor has some drawbacks:
It does not handle static methods and properties:
While PHP does have a __callStatic() magic method it does not (as yet) have magic methods to set and get static properties. Furthermore the closure route cannot be used with __callStatic; if you try to call a private or protected static method in a closure, PHP will throw an error.
Despite these drawbacks the Object Doctor can be used effectively to test your PHP code. After all you wouldn’t want to change a property or method from private to public just so that you can test it.