Encapsulation in OOP
Encapsulation is a concept where data and methods that access and mutate this data are enclosed in a single unit like a capsule. In PHP, this capsule is the object or class.
The capsule or the object will have the ability to keep its data safe from being read or manipulated, using the concept of visibility.
Visibility in PHP
To be able to control what data or functions the developer can access or use in an object in PHP, the public
, protected
, and private
keywords can be prefixed before the function
keyword in the function declaration, or before the property name declaration:
private
– Only the codes within the object can access this function or propertyprotected
– Any object extending this class will be allowed access to the function or propertypublic
– Any object user is allowed to access the property or method
What benefits do we developers get from this, then? We’ll get to know this in a bit.
...