This is old-hat to some people, but it's still a nice trick.
PHP has long supported Java-esque property and method access control. Object properties and methods may be marked public
, protected
, or private
to control what other code may access them. The general recommendation for years is that properties should be non-public in almost all cases, unless you're using the new readonly
flag in PHP 8.1.
(There's a good case to be made that object-level encapsulation is the wrong model in the first place, and package-level visibility is the superior model. I happen to agree with that argument, but that's neither here nor there for the time being.)
Most of the time, you want to respect the visibility set by the code's author. It's telling you how an object should be used, and if you do otherwise you're on your own. However, there are cases in meta-programming situations where you need to be able to bypass the visibility in order to manipulate the state of an object in a dynamic fashion. The most common scenarios are serialization, de-serialization, hydration from an ORM, and similar.
Continue reading this post on Hive.