Php Object-Oriented Learning Tutorial 5 9. encapsulation
Encapsulation is one of the three main features of object-oriented programming. encapsulation is to combine object attributes and services into an independent
The same unit, and try to hide the internal details of the object, which has two meanings: 1. combine all attributes of the object and all services in one
To form an inseparable independent unit (that is, an object ). 2. information hiding, that is, hiding the internal details of the object as much as possible.
Form a boundary (or form a barrier), and retain only limited external interfaces to associate them with the outside.
The encapsulation principle is reflected in the software: the internal data (attributes) of the object cannot be freely accessed for parts other than the object ),
This effectively avoids the "cross-infection" caused by external errors, so that software errors can be localized, greatly reducing the difficulty of error detection and troubleshooting.
Degree.
Let's explain it with an example. if a person's object has attributes such as age and salary, the attributes such as personal privacy do not want
Let others get it at will. if you don't use encapsulation, others can get it if they want to know it, but if you encapsulate it
Then, others will not be able to obtain the encapsulated attributes, unless you say it yourself, otherwise others will not be able to get it.
For example, a personal computer has a password, so you don't want others to log on, copy and paste it in your computer.
There is also an object like a person. the attributes of height and age can only be increased by oneself, but cannot be assigned randomly by others.
Use the private keyword to encapsulate attributes and methods:
Original members:
Var $ name; // declare the name of a person var $ sex; // declare the gender var $ age; // declare the person's age function run (){... ... .}
Changed to Encapsulation:
Private $ name; // encapsulate the name of a person using the private keyword private $ sex; // encapsulate the gender of a person using the private keyword private $ age; // encapsulate the age of a person using the private keyword private function run (){... ... } // Encapsulate the human walking method with the private keyword
Note: as long as there are other keywords before the member attribute, the original keyword "var" should be removed ".
You can encapsulate a member (member attribute and member method) in private mode. The encapsulated members cannot be out of the class.
The following code produces an error:
Class Person {// The following is the member attribute private $ name of a Person; // The name of a Person, which is private and encapsulated with private $ sex; // gender of a Person, private $ age is encapsulated by private. // The age of the person is encapsulated by private. // function say () {echo "My name is: ". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";}// This person's walking method is encapsulated in private function run () {echo" this person is walking ";}} // instantiate a Person's instance object $ p1 = new Person (); // If you try to assign a value to a private property, an error will occur. $ p1-> name = "Zhangsan "; $ p1-> sex = "male"; $ p1-> age = 20; // An error occurred while trying to print the private property. echo $ p1-> name."
"; Echo $ p1-> sex ."
"; Echo $ p1-> age ."
"// Try to print the private member method, and the result will be incorrect $ p1-> run ();
Output result:
Fatal error: Cannot access private property Person::$nameFatal error: Cannot access private property Person::$sexFatal error: Cannot access private property Person::$ageFatal error: Cannot access private property Person::$nameFatal error: Call to private method Person::run() from context ''
From the instance above, we can see that private members cannot be accessed externally, because private members can only
For example, the $ p1 object wants to describe its private attributes and access the private attributes in the say () method,
This is acceptable. (No access control is added. The default value is public and can be accessed anywhere)
// This person can talk about his/her own private Attributes. here, he can also access the private method function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
"; // Here you can also access the private method // $ this-> run ();} because the member method say () is public, therefore, we can call the say () method outside the class and change the code above. class Person {// The following is the member attribute private $ name of the Person; // the name of a person is private and encapsulated with private $ sex. // The gender of a person is private and private $ age. // The age of a person is private, in the private encapsulation, // defines a constructor parameter to assign values to the private attribute name $ name, gender $ sex and age $ age. function _ construct ($ name, $ sex, $ age) {// The $ name passed in by the constructor is used to assign the initial value $ this-> name = $ name to the private member attribute $ this-> name = $ name; // The $ sex passed in by the constructor is used to assign the attribute $ this-> sex to the private member $ this-> sex = $ sex; // use the constructor to assign the initial value $ this-> age to the private member attribute $ this-> age = $ age ;} // This person can talk about his/her own private Attributes. here, he can also access the private method function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";}}// Create three objects $ p1, p2, and $ p3 through the constructor, name, gender, and age $ p1 = new Person ("zhang san", "male", 20); $ p2 = new Person ("Li Si ", "Female", 30); $ p3 = new Person ("Wang Wu", "male", 40 ); // access the method of speaking in the $ p1 object below $ p1-> say (); // access the method of speaking in the $ p2 object below $ p2-> say (); // the following method is used to access the $ p3 object $ p3-> say ();
Output result:
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: 40
Because the constructor is the default public method (the constructor should not be set to private), it can be accessed outside the class,
In this way, you can use the constructor to create an object. In addition, the constructor is also a function in the class, so you can use the constructor
Some attributes assign initial values. The Say () method is public by default, so it can be accessed outside and said his own private
.
From the above example, we can see that private members can only be used inside the class and cannot be directly accessed outside the class,
However, you have access permissions within the class, so sometimes you need to assign values to and read private attributes outside the class.
The constructor is used to provide some accessible interfaces to the outside of the class. in the preceding example, the constructor is a value assignment method, but the constructor only
Assign values when creating an object. if we want to assign values to an existing object
If you still use the constructor to pass the value, a new object is created, which is not an existing object.
. Therefore, we need to make some interfaces that can be accessed externally for private attributes, so that when an object exists,
Change and access the attribute value. However, note that only attributes that need to be changed by the external user do this. the attribute that does not want to be accessed by the external user is
Without such an interface, you can achieve the purpose of encapsulation. all the functions are implemented by the object itself, and provide as much information as possible for the outside.
Few operations.
If an interface is provided for the class, you can provide the setting and obtaining methods for private attributes outside the class to operate on private attributes.
For example:
Prvate $ age; // private property age function setAge ($ age) // provides a public age setting method for external users {if ($ age <0 | $ age> 130) // when assigning values to attributes, to avoid setting invalid values to the property return; $ this-> age = $ age;} function getAge () // provide a public method for obtaining the external age {return ($ this-> age );}
The above method sets and obtains values for a member attribute. of course, you can use the same method for each attribute.
Assign values and values to complete access outside the class.
10. _ set () _ get () _ isset () _ unset () application of four methods
In general, the class attribute is always defined as private, which is more in line with the actual logic. However, read and assign values to attributes
Operations are very frequent. Therefore, in PHP5, we predefine the two functions "_ get ()" and "_ set ()" to obtain and assign values to them.
Attribute, and check the "_ isset ()" of the attribute and the method "_ unset ()" for deleting the attribute ()".
In the previous section, we set and obtain each attribute. in PHP5, we provided a special attribute setting method.
Value and the method for getting the value, "_ set ()" and "_ get ()". These two methods do not exist by default, but exist by hand.
Like the constructor (_ construct (), which is added to the class, can be added to the class as follows:
To add these two methods, of course, you can also add them in your own style:
// _ Get () is used to obtain private attributes.
Private function _ get ($ property_name) {if (isset ($ this-> $ property_name) {return ($ this-> $ property_name );} the else {return (NULL) ;}// _ set () method is used to set the private property private function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value ;}
_ Get () method:
This method is used to obtain the attribute values of private members. there is a parameter that is passed in to the member attributes you want to obtain.
Returns the obtained property value. this method does not need to be manually called, because we can also make this method private
Some methods are called automatically when the private attribute is directly obtained. Because private attributes have been encapsulated, it cannot
It is incorrect to directly obtain the value (for example, "echo $ p1-> name"), but if you add this
When the "echo $ p1-> name" statement is used to directly obtain the value, _ get ($ property_name) is automatically called)
Method to pass the attribute name to the parameter $ property_name. through the internal execution of this method, the private attribute we passed in is returned.
. If the member attributes are not encapsulated as private, the object itself will not automatically call this method.
_ Set () method: This method is used to set values for private member attributes. There are two parameters. The first parameter is set for you.
The attribute name of the value. The second parameter is the value to be set for the property. no return value is returned. We do not need to manually call this method,
It can also be made private and automatically called when the private property value is directly set. Similarly, the private property has been encapsulated.
The _ set () method is not allowed, for example, $ this-> name = 'hangsan '.
If you add the _ set ($ property_name, $ value) method to the class, when you directly assign values to private properties,
It will be called automatically, pass the attribute such as name to $ property_name, and pass the value "zhangsan" to $ value through
The execution of this method achieves the purpose of assigning values. If the member attributes are not encapsulated as private, the object itself will not automatically call this
Methods. In order not to pass in invalid values, you can also make a judgment in this method. The code is as follows:
"; If (isset ($ this-> $ property_name) {return ($ this-> $ property_name);} else {return (NULL );}} // _ set () is used to set the private property private function _ set ($ property_name, $ value) {echo "when setting the private property value directly, the _ set () method is automatically called to assign values to private attributes.
"; $ This-> $ property_name = $ value ;}}$ p1 = new Person (); // operations that directly assign values to private properties automatically call _ set () method $ p1-> name = "zhang san"; $ p1-> sex = "male"; $ p1-> age = 20; // directly obtain the value of the private attribute, the _ get () method is automatically called, and the echo "name :". $ p1-> name."
"; Echo" gender: ". $ p1-> sex ."
"; Echo" age: ". $ p1-> age ."
";?>
Program execution result:
When the private property value is directly set, the _ set () method is automatically called to assign values to the private property. when the private property value is directly set, the _ set () method is automatically called () when you directly set the private property value, the _ set () method is automatically called to assign values to the private property. when you directly obtain the private property value, the _ get () method name is automatically called: Zhang San automatically calls the _ get () method gender when obtaining the private property value directly: when a male directly obtains a private property value, he automatically calls the _ get () method. Age: 20
If the above code does not contain the _ get () and _ set () methods, the program will fail because private members cannot be operated on outside the class,
The above code automatically calls the _ get () and _ set () methods to help us directly access the encapsulated private members.
_ Isset () method: before reading this method, let's take a look at the application of the "isset ()" function. isset () is used to determine whether the variable is set
If the input variable exists, true is returned; otherwise, false is returned. If
Use the "isset ()" function outside an object to determine whether the members in the object are set. can they be used? There are two types
If the members in the object are public, we can use this function to determine the member attributes. if the members are private members
Attribute, this function does not work, because the private is encapsulated and invisible to the outside. Then we cannot
Use the "isset ()" function outside the object to determine whether the private member attribute is set? Yes. you only need to add
A "_ isset ()" method is enough. when the "isset ()" function is used outside the class, it is used to determine whether private members in the object are set.
The "_ isset ()" method in the class is automatically called to complete this operation. The "_ isset ()" method can also be used.
Make it private. You can add the following code to the class:
Private function _ isset ($ nm) {echo "is automatically called when the isset () function is used outside the class to determine the private member $ nm.
"; Return isset ($ this-> $ nm );}
_ Unset () method:
Before reading this method, let's take a look at the "unset ()" function and the "unset ()" function.
The value is used to delete the specified variable and return true. the parameter is the variable to be deleted. If you delete an object
Is it possible to use the "unset ()" function for internal member attributes? there are two situations:
If it is public, you can use this function to delete the public attributes of an object outside the object. if the member attributes of the object are private,
I have no permission to delete this function, but if you add the "_ unset ()" method to an object
You can delete the private member attributes of an object outside the object. After the "_ unset ()" method is added to the object,
When the "unset ()" function is used outside the object to delete the private member attributes inside the object, the "_ unset ()" function is automatically called.
We delete the private member attributes inside the object. this method can also be defined as private within the class. Add the following to the object:
The following code can be used:
Private function _ unset ($ nm) {echo "automatically called when the unset () function is used outside the class to delete private members
"; Unset ($ this-> $ nm);} Let's look at a complete instance:
$ Property_name) {return ($ this-> $ property_name);} else {return (NULL) ;}// _ set () the private function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value;} // _ isset () method: when the private function _ isset ($ nm) {echo "isset () function is used to determine a private member, it is automatically called.
"; Return isset ($ this-> $ nm);} // _ unset () method private function _ unset ($ nm) {echo "automatically called when the unset () function is used outside the class to delete private members
"; Unset ($ this-> $ nm) ;}$ p1 = new Person (); $ p1-> name =" this is a person name "; // when the isset () function is used to determine private members, the _ isset () method is automatically called to help us complete the measurement, the returned result is trueecho var_dump (isset ($ p1-> name ))."
"; Echo $ p1-> name ."
"; // When the unset () function is used to delete a private member, the _ unset () method is automatically called to help us complete the deletion of the name private property unset ($ p1-> name ); // if the row is deleted, no echo $ p1-> name;?> is output.
Output result:
When the isset () function is used to determine private members, it automatically calls bool (true) this is a person name when unset () is used outside the class () when a private member is deleted, the functions automatically call the following: _ set (), _ get (), _ isset (), and _ unset () these four methods are added to the object and are automatically called as needed to perform operations on private attributes inside the object outside the object.
The above is the content of php Object-Oriented Learning Tutorial 5. For more information, see PHP Chinese network (www.php1.cn )!