SoFunction
Updated on 2025-04-09

PHP object-oriented strategy (V) Encapsulation

9. Encapsulation
Encapsulation is one of the three major features in object-oriented programming. Encapsulation is to combine the properties and services of objects into one
Independent identical units and conceal the internal details of the object as much as possible, including two meanings: 1. Put all the properties of the object and all
The departmental services are combined to form an inseparable independent unit (i.e., object). 2. Information is concealed, that is, as concealed as possible
The internal details of the image form a boundary (or a barrier) to the outside, and only a limited external interface is retained to make it external.
The department has contacted.
The principle of encapsulation in software is to ensure that parts other than objects cannot access the internal data of the object at will.
(Properties), thus effectively avoiding the "cross-infection" of external errors, allowing software errors to be localized and greatly reduced
Less difficulty in checking and troubleshooting.
Let's use an example to illustrate. If a person's object has attributes such as age and salary, such as personal privacy
I don't want others to get it at will. If you don't use encapsulation, then others can get it if they want to know, but like
If others cannot obtain the encapsulated attributes after you encapsulate it, no one else can do it unless you tell it yourself.
Get the method
For example, personal computers have a password, and don’t want others to log in at will, copy and
Paste. Also, the height and age attributes of people can only be increased by themselves, and others cannot be allowed to do so.
assignments and so on.
Use the private keyword to encapsulate properties and methods:
Original members:
var $name; //Declare the name of the person
var $sex; //Declare the gender of the person
var $age; //Declare the age of the person
function run(){… … .}
Change to encapsulation form:
private $name; //Encapsulate the person's name using the private keyword
private $sex; //Encapsulate the gender of a person using the private keyword
private $age; //Use the private keyword to encapsulate a person's age
private function run(){… … } //Use the private keyword to encapsulate the walking method of a person
Note: As long as there are other keywords in front of the member attribute, the original keyword "var" must be removed.
Through private, people's members (member attributes and member methods) can be encapsulated. Members on the encapsulation cannot
It is accessed directly outside the class, and only the object can access it itself; the following code will produce an error:
Code snippet
Copy the codeThe code is as follows:

class Person{
//The following are the member attributes of people
private $name; //The person's name is encapsulated by private
private $sex; //The gender of a person is encapsulated by private
private $age; //The age of a person is encapsulated by private
//How can this person speak
function say(){
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."<br>";
}
//The way this person can walk is encapsulated by private
private function run(){
echo "This person is walking";
}
}
//Instantiate an instance object of a person
$p1=new Person();
//Try to assign values ​​to private attributes, an error will occur as a result.
$p1->name="Zhang San";
$p1->sex="male";
$p1->age=20;
//Try to print private attributes, an error will occur as a result
echo $p1->name.”<br>”;
echo $p1->sex.”<br>”;
echo $p1->age.”<br>”
//Try to print private member method, an error will occur as a result
$p1->run();

The output result is:
Fatal error: Cannot access private property Person::$name
Fatal error: Cannot access private property Person::$sex
Fatal error: Cannot access private property Person::$age
Fatal error: Cannot access private property Person::$name
Fatal error: Call to private method Person::run() from context ''
From the above example, we can see that private members cannot be accessed externally because private members can only be accessed in this object
Access internally, for example, the $p1 object wants to tell its private attributes by itself, and access it in the say() method
I asked about the private attributes, so it is OK. (No access control is added, the default is public, and you can access it anywhere
ask)
Code snippet
Copy the codeThe code is as follows:

//The method that this person can speak, tell his own private attributes, and you can also access the private method here
function say(){
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."<br>";
//You can also access private methods here
//$this->run();
}

Because the member method says() is public, it is OK for us to call the say() method outside the class, change the above
code;
Code snippet
Copy the codeThe code is as follows:

class Person{
//The following are the member attributes of people
private $name; //The person's name is encapsulated by private
private $sex; //The gender of a person is encapsulated by private
private $age; //The age of a person is encapsulated by private
//Define a constructor parameter to assign private attribute name $name, gender $sex and age $age
function __construct($name, $sex, $age){
// Assign the initial value to the private member attribute $this->name through the constructor method
$this->name=$name;
//The $sex passed in through the constructor method assigns the initial value to the private member attribute $this->sex
$this->sex=$sex;
// Assign the initial value to the private member attribute $this->age through the constructor method
$this->age=$age;
}
//The method that this person can speak, tell his own private attributes, and you can also access the private method here
function say(){
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."<br>";
}
}
//Create 3 objects $p1, p2, and $p3 through the construction method, and pass in three different real parameters as name, gender and age respectively.
$p1=new Person("Zhang San", "Male", 20);
$p2=new Person("Li Si", "female", 30);
$p3=new Person("Wang Wu", "Male", 40);
//The following access to the speaking method in the $p1 object
$p1->say();
//The following access to the speaking method in the $p2 object
$p2->say();
//The following access to the speaking method in the $p3 object
$p3->say();

The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
Because the constructor is the default public method (the constructor should not be set to private), you can access it outside the class
Asked, this way you can use the constructor to create objects. In addition, the constructor is also a function in the class, so you can use constructor
Create method assign initial values ​​to private attributes. The Say() method is public by default, so it can also be accessed outside.
Expose his own private attributes.
From the above example, we can see that private members can only be used inside the class and cannot be directly used outside the class
Access, but access is available inside the class, so sometimes we need to assign values ​​and
Read it, that is, provide some accessible interfaces to the outside of the class. In the above example, the construction method is an assignment shape.
But the construction method is just to assign values ​​when creating an object. If we already have an existing object, we want to do this
Assign values ​​to an existing object. At this time, if you also use the constructor to pass the value, then you create a
The new object is not the existing object. So we need to do some private attributes that can be accessed externally
The purpose of the interface is to change and access the value of the attribute when the object exists, but be careful that only the external one needs to be
This is done only when the properties that are changed. The properties that do not want to be accessed outside do not use such an interface, so that the encapsulation can be achieved.
Purpose: All functions are completed by the object itself, providing as few operations as possible to the outside world.
If an interface is provided to the outside of the class, a private property can be provided with setting methods and obtaining methods outside the class to operate the private property to
Have attributes. For example:
Code snippet
Copy the codeThe code is as follows:

private $age; //Private attribute age
function setAge($age) {
// Provide an external method to set age by public
if($age<0 || $age>130) // When assigning values ​​to attributes, in order to avoid illegal values ​​set to attributes
return;
$this->age=$age;
}
function getAge(){ // Provide an external method to obtain age by publicly
return($this->age);
}

The above method is to set and get the value for a member property, of course you can use the same method for each property.
It performs the operation of assignment and obtaining values, and completes the access work outside the class.