PHP:OOP Property Hiding & Type Hinting Overview [Tutorial]

Prince

[ Verified Seller ]
Staff member
Trusted Seller
Joined
11 yrs. 6 mth. 27 days
Messages
5,381
Reaction score
18,380
Age
45
Wallet
11,590$
Introduction:

Property hiding in PHP (or I guess in any other language which supports an object model as well) is massively used and its idea is almost absolutely self-explanatory. However, since I started my series some time ago, I'll go through it as well. It is mainly the basis of my future tutorials from the series which would include some of the most commonly used templates in PHP. So let's begin with our examples.

Let's take this class for instance (Calories.php):

Code:
Please, Log in or Register to view codes content!
Suppose the purpose of the class is to calculate the amount of calories of a person based on his age and gender (no quite original but that's what I managed to come up with). Now these properties are public which automatically means that if we happen to have an instance of the class Calories, everyone from outside can access it. Let's go to index.php where our instance is.

Code:
Please, Log in or Register to view codes content!
That is just how one would go about for accessing it and inserting arbitrary data. But a worse scenario would be if the guy was to define a boolean value.
Code:
Please, Log in or Register to view codes content!
In that way we have a private property which is in the scope of the class but it becomes publicly accessible and in those loops we can modify, check and whatever we want to validate in the data.
 
Top Bottom