Home >Backend Development >PHP Tutorial >PHP object-oriented guide (5) Encapsulation_PHP tutorial
9. Encapsulation
Encapsulation is one of the three major characteristics of object-oriented programming. Encapsulation is to combine the properties and services of an object into an
independent and identical unit, and try to Concealing the internal details of an object has two meanings: 1. Combining all the attributes and all services of the object to form an indivisible independent unit (i.e. object). 2. Information hiding, that is, hiding the internal details of the object as much as possible, forming a boundary [or forming a barrier] to the outside world, and retaining only a limited external interface to connect it with the outside world. The reflection of the principle of
encapsulation in software is that it requires that parts other than the object cannot access the internal data
(attributes) of the object at will, thereby effectively avoiding the "cross-infection" of external errors and making it Software errors can be localized, greatly reducing the difficulty of error detection and troubleshooting.
Let’s use an example to illustrate. Suppose a person’s object has attributes such as age and salary. Such personal privacy attributes
are not accessible to other people. If you don’t use encapsulation, Then others can get it if they want to know, but
if you encapsulate it, others will have no way to obtain the encapsulated attributes. Unless you tell it yourself, there is no way for others to
get it.
For another example , every personal computer has a password. If you don’t want others to log in at will, copy and
paste it into your computer. Also, for objects like people, the attributes of height and age can only be increased by oneself, and cannot be assigned values arbitrarily
by others, etc.
Use the private keyword to encapsulate properties and methods:
Original members:
var $name; //The name of the declarant
var $sex; //The gender of the declarant
var $age; //Declare the person’s age
function run(){… … .}
Change to encapsulated form:
private $name; //Use the private keyword for the person’s name Encapsulate
private $sex; //Encapsulate the person’s gender using the private keyword
private $age; //Encapsulate the person’s age using the private keyword
private function run(){… … } //Use the private keyword to encapsulate a person’s walking method
Note: As long as there are other keywords in front of the member attributes, the original keyword "var" must be removed.
You can encapsulate human members (member attributes and member methods) through private. The members in the package cannot
be directly accessed from outside the class, only the object itself can access it; the following code will generate an error:
Code snippet
Copy code