Tearing up the rulebook of Object Oriented Programming in PHP

Nigel Hurnell
Jan 12 · 2 min read

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:

PhpObjectDoctor constructor
PhpObjectDoctor constructor

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:

PhpObjectDoctor magic call method
PhpObjectDoctor magic call method

To set or get properties of the patient we use the magic __set and __get methods:

PhpObjectDoctor magic setter
PhpObjectDoctor magic setter
PhpObjectDoctor magic getter
PhpObjectDoctor magic getter

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade