HomePHP Protecting PHP 5 Class Data with Member Visibility
Protecting PHP 5 Class Data with Member Visibility
If you ever have the chance to gather a group of PHP programmers in a big room and ask them whether they find it hard to build classes with PHP, the invariable answer would probably be a resounding "No!" And admittedly, they’d be absolutely right, since PHP allows you to work with classes, methods, and properties in a pretty straightforward way. But there's more to programming with classes, as this article series will explain.
As soon as a PHP developer masters the basic principles of object-oriented programming, s/he is faced with a challenging barrier of concepts that at first sight, might sound intimidating even to the bravest programmer: composition and aggregation, polymorphism and inheritance, object factories and singletons, and the list goes on and on. How can all these things be properly digested?
Well, in all these cases, an adequate balance between the corresponding theory and thorough practice can be the correct way to tackle the different facets that compose the so-called object-oriented paradigm, even though this learning process can take a long time.
The previous concept can also be applied successfully when it comes to defining the visibility of properties and methods in PHP classes. As you possibly know, aside from declaring a certain number of properties and implementing concrete methods within a given PHP class, it’s also possible (and highly recommended) to specify if they’ll be available globally, or restricted to the scope of the class itself and its eventual subclasses.
Using the jargon of object-oriented programming, this capacity is widely known as member visibility. This capacity allows PHP programmers to establish whether the set of methods and properties of a specific class will be public, protected, or private. This easily permits you to set different levels of “protection” for certain data members.
In plain terms, it isn’t possible to specify the grade of visibility that a member of a class will have in PHP 4, but similar results can be achieved with a bit of willpower. On the other hand, the object model of PHP 5 incorporates the “public,” “protected,” and “private” keywords, which can be used to indicate the visibility of methods and properties declared by a class.
Having briefly introduced the concepts that surround the implementation of “member visibility” in PHP 5, in this group of articles I’ll be taking a closer look at this fundamental topic, so you can learn by way of copious hands-on examples how to permit and restrict the access to the data of your PHP 5 classes.
Ready to begin this educational journey? Let’s get started!