Php object-oriented full strategy (5) encapsulation _ PHP Tutorial

Source: Internet
Author: User
Php object-oriented full strategy (5) encapsulation. 9. encapsulation is one of the three main features of object-oriented programming. encapsulation is to combine object attributes and services into an independent unit, and try to hide the object's internal 9. encapsulation
Encapsulation is one of the three main features of object-oriented programming. encapsulation is to combine object attributes and services into
Independent of the same unit, and try to hide the internal details of the object, which has two meanings: 1. all attributes of the object and
Services are combined to form an inseparable independent unit (that is, an object ). 2. information hiding, that is, try to hide
The internal details of the image form a boundary (or form a barrier), and only retain limited external interfaces
Department.
The encapsulation principle is reflected in the software: the internal data 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 and greatly reduced.
This reduces the difficulty of error detection and troubleshooting.
Let's explain it with an example. assume that a person's object has attributes such as age and salary, such as personal privacy attributes.
You don't want others to get it at will. if you don't use encapsulation, you can get it if you want to know it.
If you encapsulate it, others will not be able to obtain the encapsulated attributes unless you say it yourself, otherwise others will not do it.
Method
For example, a personal computer has a password, so you don't want others to log on at will. copy and
Paste. There is also a person-like object. the attributes of height and age can only be increased by oneself, and cannot be made at will by others.
.
Use the private keyword to encapsulate attributes and methods:
Original members:
Var $ name; // The name of the declarer
Var $ sex; // declare the gender of a person
Var $ age; // declare the person's age
Function run (){... ... .}
Changed to Encapsulation:
Private $ name; // encapsulate a person's name 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
It is directly accessed outside the class, and only the object can be accessed by itself. the following code produces an error:
Code snippet

The code is as follows:


Class Person {
// The following are the member attributes of a person.
Private $ name; // The name of a person, which is encapsulated by private
Private $ sex; // the gender of a person, which is encapsulated by private
Private $ age; // age of a person, which is encapsulated by private
// How this person can speak
Function say (){
Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";
}
// The way this person can walk is encapsulated by private
Private function run (){
Echo "this person is walking ";
}
}
// Instantiate a person's instance object
$ P1 = new Person ();
// Try to assign values to private attributes, and the result will be incorrect
$ P1-> name = "James ";
$ P1-> sex = "male ";
$ P1-> age = 20;
// An error occurs when you try to print a 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: $ 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 instance above, we can see that private members cannot be accessed externally, because private members can only
Internal access by yourself. for example, the $ p1 object wants to describe its private property and access it in the method of "say ()".
I asked about private Attributes. this is OK. (No access control is added. The default value is public, and access is allowed anywhere.
Question)
Code snippet

The code is as follows:


// This person can talk about his/her own private attributes and access the private method here.
Function say (){
Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";
// You can also access private methods here
// $ This-> run ();
}


Because the Member method 'Say () 'is public, we can call the 'Say ()' method outside the class.
Code;
Code snippet

The code is as follows:


Class Person {
// The following are the member attributes of a person.
Private $ name; // The name of a person, which is encapsulated by private
Private $ sex; // the gender of a person, which is encapsulated by private
Private $ age; // age of a person, which is encapsulated by private
// Define a constructor parameter to assign values to the 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 $ name passed in by the constructor
$ This-> name = $ name;
// The $ sex passed in through the constructor is used to assign the initial enable value to the private member attribute $ this-> sex.
$ This-> sex = $ sex;
// Assign the initial value to the private member attribute $ this-> age through the $ age passed in by the constructor
$ This-> age = $ age;
}
// This person can talk about his/her own private attributes and access the private method here.
Function say (){
Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";
}
}
// Create three objects $ p1, p2, and $ p3 by using the constructor, and input three different real parameters: 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 );
// The following method of accessing the $ p1 object
$ P1-> say ();
// The following method of accessing the $ p2 object
$ 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 my age is: 40
Because the constructor is the default public method (the constructor should not be set to private), you can access
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
Assign an initial value to a private attribute. The Say () method is public by default, so it can be accessed outside.
Out of 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 permitted within the class, so sometimes we need to assign values to private attributes and
Read out, that is, to provide some accessible interfaces to the outside of the class. in the above example, the constructor is a type of value assignment.
But the constructor only assigns a value when creating an object. if we already have an existing object
An existing object is assigned a value. at this time, if you use the constructor to pass the value,
The new object is not an existing object. Therefore, we need to make some private attributes that can be accessed externally.
Interface, the purpose is to change and access the attribute value when the object exists.
This is the only way to do this. if you do not want the attribute accessed outside to do not use this interface, the encapsulated
Purpose: all functions are completed by the object itself, and provide as few operations as possible for the outside.
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.
Has Attributes. for example:
Code snippet

The code is as follows:


Prvate $ age; // private property age
Function setAge ($ age ){
// Provide a public age setting method for external users
If ($ age <0 | $ age> 130) // when assigning a value to an attribute, to avoid setting an invalid value to the attribute
Return;
$ This-> age = $ age;
}
Function getAge () {// provides a public method for obtaining the age.
Return ($ this-> age );
}


The above method is to set and obtain values for a member attribute. of course, you can also use the same method for each attribute
It assigns values and values to complete the access work outside the class.

Encapsulation is one of the three main features of object-oriented programming. encapsulation is to combine object attributes and services into an independent unit of the same, and to conceal the objects as much as possible...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.