PHP Object-oriented Learning Tutorial 5

Source: Internet
Author: User
9. Encapsulation
Encapsulation is one of the three characteristics of object-oriented programming, which combines the properties and services of an object into a separate
The same unit, and as far as possible to conceal the inner details of the object, contains two meanings: 1. Combine all the properties of an object with all services in one
To form an indivisible independent unit (i.e. object). 2. Information concealment, that is, as far as possible to conceal the internal details of the object, the shape
into a boundary (or form a barrier), leaving only a limited external interface to make it contact with the outside.
The principle of encapsulation is reflected in the software by requiring that parts other than objects not arbitrarily access the object's internal data (attributes),
Thus effectively avoids the external error of its "cross-infection", so that software errors can be localized, greatly reducing the difficulty of error-checking and debugging
Degree.
Use an example to illustrate, if the object of a person has age and wages and other attributes, such as the nature of personal privacy is not
Let others get it at will, and if you don't use encapsulation, you'll get it if you want to know it, but if you package it
Other people will not be able to get the properties of encapsulation, unless you say it yourself, otherwise people can not get.
For example, personal computers have a password, do not want to let others random landing, in your computer copy and paste.
There is a human object, height and age attributes, can only be the growth of their own, can not let others arbitrarily assigned to the value and so on.
Use the Private keyword to encapsulate properties and methods:
The original member:

var $name; The name of the Claimant Var $sex; The gender Var $age of the claimant; The declarator's age function run () {...}

Change to package form:

Private $name; The name of the person using the private keyword to encapsulate the private $sex; Use the Private keyword to encapsulate the person's gender $age; Use the Private keyword to encapsulate a person's age private function run () {...}//Take a person's way of walking using the Private keyword for encapsulation

Note: The original keyword "var" should be removed as long as there are other keywords in front of the member property.
By private, you can encapsulate a person's members (member properties and member methods). The members on the package cannot be outside the class
Directly accessible to the object itself, the following code generates an error:

Class person{//Below is the member property of the person private $name,//person's name, is the private package on the private $sex,//person's gender, was private package on the private $age;//person's age, By private package on//This person can speak method function say () {echo "My name is:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. " <br> ";} This person can walk the way, was the private package on a private function run () {echo "This person is walking";}} Instantiate an Instance object $p1=new person ();//try to assign a value to a private property, the result will be error $p1->name= "Zhang San"; $p 1->sex= "male"; $p 1->age=20;// Attempting to print a private property, the result will be an error echo $p 1->name. " <br> "Echo $p 1->sex." <br> "Echo $p 1->age." <br> "//try to print the private member method, the result will be error $p1->run ();

The output is:

Fatal Error:cannot Access Private Property Person:: $nameFatal The Error:cannot access private property Person:: $sexFatal err Or:cannot Access Private Property Person:: $ageFatal error:cannot Access private:: $nameFatal Error:call To Private Method Person::run () from context '

From the above example, it can be seen that private members cannot be accessed externally, because private members can only be accessed from within this object, for example, $p 1 The object itself wants to say his private property, in say () This method accesses the private property,
this is possible. (No access control is added, default is public, accessible anywhere)

This person can speak in a way that says his own private property, and here can also access the Private method function say () {echo "My name is:". $this->name. "Gender:". $this->sex. "My Age is:". $ This->age. " <br> ";//The Private method can also be accessed here//$this->run ();} Because the Member method say () is public, we call the Say () method outside of the class to be able to change the above code; class person{//below is the member property of the person private $name;//person's name, was private package on the private $ Sex The gender of the person, the private package on the private $age; The age of the person, the private package on the//define a constructor method parameter for the private property name $name, gender $sex and age $age assignment function __construct ($name, $sex, $age) {// The $name passed in by the constructor method assigns the value $this->name= $name to the private member property $this->name,//$sex to the private member property $this->sex by constructing the method to assign the initial value $this- >sex= $sex;//$age to the Private member property $this->age the value $this->age= $age by the constructor method;} This person can speak in a way that says his own private property, and here can also access the Private method function say () {echo "My name is:". $this->name. "Gender:". $this->sex. "My Age is:". $ This->age. " <br> ";}} Create 3 objects by constructing the method $p1, P2, $p 3, passing in three different arguments for name, gender, and age $p1=new person ("Zhang San", "male"), $p 2=new person ("John Doe", "female"), $p 3=new Person ("Harry", "male", 40);//The following access to the $p1 object in the speech method $p1->say ();//The following access to the $p2 object in the speech method $p2->say ();//The following access to the $p3 object in the speech method $p3->say ();

The output is:

My name is: Zhang San Sex: Male my age is: 20 My name is: John Doe sex: Female my age is: 30 My name is: Harry Sex: Male My age is: 40

Because the constructor method is the default public method (the construction method is not set to private), it can be accessed outside the class,
This allows you to create objects using the constructor method, which is also a function within the class, so you can use the constructor method to give private
Some attributes are assigned an initial value. Say () method is the default public, so can also be accessed outside, to say his own private genus
Of
From the above example, we can see that the private members can only be used inside the class, and cannot be accessed directly from outside the class.
However, there is access to the inside of the class, so sometimes we need to assign and read the private property outside of the class, and
is to provide some accessible interfaces to the outside of the class, the constructor method in the example above is a form of assignment, but the construction method only
is to assign a value when creating an object, if we already have an existing object and want to assign a value to the existing object, this time
If you also use the constructor method to pass the value, then a new object is created, not the existing
It's like. So we have to do some external access to the private properties of the interface, the purpose is to be able to exist in the case of the object,
Change and access the value of the property, but be aware that only the properties that need to be changed externally do so, and do not want the properties that are accessed outside to be
Do not do such an interface, so that it can achieve the purpose of encapsulation, all the functions are objects themselves to complete, to the outside to provide as far as possible
Less operation.
If you provide an interface outside the class, you can manipulate the private property by providing a set method and a Get method outside the class for the private property.
For example:

Prvate $age; The private attribute Age function setage ($age)//provides a public setting age for the external method {if ($age <0 | | $age >130)//When assigning a value to an attribute, in order to avoid an illegal value set to the property return;$ This->age= $age;} function getage ()//provides a method for the external public acquisition Age {return ($this->age);}

The method above is to set and get values for a member property, and of course you can do it in the same way for each property
Assignment and value operation, complete the access work outside the class.
Application of four methods of 10.__set () __get () __isset () __unset ()
In general, it is more realistic logic to always define the properties of a class as private. However, the reading and assignment of the property
Operations are very frequent, so in PHP5, two functions "__get ()" and "__set ()" are predefined to obtain and assign their
property, and the method "__unset ()" That examines the properties ' __isset () and deletes the property.
In the previous section, we set and get the method for each property, and in PHP5 we provided a special set for the property
Values and methods of getting the values, "__set ()" and "__get ()" are two methods that do not exist by default, but our hands
Work is added to the class, like the construction Method (__construct ()), the class is added to exist, you can follow the way
To add these two methods, of course, can also be added according to personal style:
The __get () method is used to get the private property

Private Function __get ($property _name) {if (Isset ($this-$property _name)) {return ($this-$property _name);} Else{return (NULL);}} The __set () method is used to set the private property __set ($property _name, $value) {$this, $property _name = $value;}

__get () Method:

This method is used to get the value of the private member property, there is a parameter, the parameter passed in the name of the member property that you want to get, return the obtained property value, this method does not have to be called manually, because we can also make this method private
some method, The object is automatically called when the private property is obtained directly. Since the private property is already encapsulated, it is not possible to
get the value directly (for example: "Echo $p 1->name"), but if you add this
method to the class, use "Echo $p 1->name" When such a statement gets the value directly, it automatically calls the __get ($property _name)
method, passes the property name to the parameter $property_name, and returns the value of our incoming private property
through the internal execution of the method. If the member property is not encapsulated as private, the object itself does not automatically call this method.
__set () Method: This method is used to set the value of the private member property, there are two parameters, the first parameter is the property name you want to set
value, the second parameter is the value to set for the property, there is no return value. This method also does not need to be called manually,
It can also be made private, is directly set the value of the private property automatically called, the same property private has been encapsulated
, if there is no __set () This method is not allowed, such as: $this->name= ' Zhangsan ', this will make an error, but
is if you add __set ($property _name, $value) to the class, and when you assign a value directly to a private property,
automatically calls it, passing the attribute such as name to $ Property_name, the value to be assigned "Zhangsan" to $value, through the implementation of
this method, to achieve the purpose of assignment. If a member property is not encapsulated as private, the object itself does not automatically call this
method. In order not to pass in illegal values, you can also make a judgment in this method. The code is as follows:

<?phpclass person{//Below is the member attribute of the person, both the private member of the package $name;//person's name private $sex;//person's gender private $age;//person's age//__get () The __get method is used to get the private property of the privacy function ($property _name) {echo "Automatically calls this __get () method <br>" When the value of the private property is obtained directly, "if (Isset ($this- > $property _name) {return ($this, $property _name);} Else{return (NULL);}} The __set () method is used to set the private property __set ($property _name, $value) {echo "Automatically calls this __set () method to assign a value to a private property when the private property value is set directly < Br> "; $this-$property _name = $value;}} $p 1=new person ();//The operation that assigns a value directly to a private property automatically calls the __set () method to assign a value $p1->name= "Zhang San"; $p 1->sex= "male"; $p 1->age=20;//get the value of the private property directly , the __get () method is called automatically, returning the value of the member property echo "Name:". $p 1->name. " <br> "; echo" Gender: ". $p 1->sex." <br> "; echo" Age: ". $p 1->age." <br> ";? >

Program execution Results:

When the private property value is set directly, the __set () method is called automatically when the private property value is set directly to the private property, the __set () method is called automatically when the private property value is set directly to the private property, the __set () method to assign a value to a private property automatically calls the __get () method name when it directly acquires the value of the private property: Zhang San automatically calls the __get () method when it directly acquires the value of the private attribute: The male automatically calls the __get () when the value of the private attribute is obtained directly. Method Age: 20

If the above code does not add the __get () and __set () methods, the program will go wrong because the private member cannot be manipulated outside the class.
The code above is automatically called by the __get () and __set () methods to help us directly access the encapsulated private members.
__isset () Method: Before looking at this method we look at the application of the "isset ()" function, Isset () is the determination of whether the variable is set
The fixed function, passing in a variable as a parameter, returns true if the passed-in variable exists, or returns false. So if
Use the "isset ()" function outside an object to determine whether a member of the object is set or not to use it? Divided into two kinds
Case, if the member inside the object is public, we can use this function to measure the member property, if it is a private member
attribute, this function does not work because the private is encapsulated and is not visible externally. Then we're not going to
Use the "isset ()" function outside the object to determine if the private member property is set? Yes, you just add it to the class.
A "__isset ()" Method is OK, when using the "isset ()" function outside the class to determine whether the private member inside the object is set
Timed, the "__isset ()" method in the class is automatically called to help us do this, and the "__isset ()" Method can also
Made private. You can add the following code to the class:

Private Function __isset ($NM) {echo] automatically calls <br> "when the Isset () function is used outside the class to measure private member $nm, return Isset ($this, $nm);}

__unset () Method:

Before we look at this method, let's take a look at the "unset ()" function, "unset ()" This letter
The function of a number is to delete the specified variable and return True, and the argument is the variable to be deleted. Then if you delete the object outside of the
Like the internal member property with the "unset ()" function can be, it is also divided into two cases, if the member property inside an object
Is public, you can use this function to delete the public properties of an object outside the object, if the object's member property is private,
I don't have permission to delete this function, but also if you add "__unset ()" To an object,
You can delete the private member property of an object outside the object. After adding the "__unset ()" method to the object,
When you use the unset () function outside an object to delete private member properties inside an object, the __unset () function is called automatically to help
We delete the private member property inside the object, and this method can be defined as private within the class. Add up and down inside the object
The code of the polygon can be:

Private Function __unset ($NM) {echo "is automatically called when the unset () function is used outside the class to remove the private member <br>"; unset ($this, $nm);} Let's look at a complete example: <?phpclass person{//Below is the person's member attribute private $name;//person's name private $sex;//person's gender private $age;//person's age//__get () The __get method is used to obtain the private property of the privacy function ($property _name) {if (Isset ($this, $property _name)) {return ($this $property _ name);} else {return (NULL);}} The __set () method is used to set the private property __set ($property _name, $value) {$this, $property _name = $value;} __isset () method automatically calls <br> "when Private function __isset ($NM) {echo" isset () function is used to determine the member, return Isset ($this, $nm);} __unset () method Private Function __unset ($NM) {echo "is automatically called when a private member is removed using the unset () function outside the class"; Unset ($this, $nm);}} $p 1=new person (); $p 1->name= "This is a person name";//When you use the Isset () function to measure a private member, the __isset () method is automatically invoked to help us complete the return result as Trueecho Var_ Dump (isset ($p 1->name)). " <br> "Echo $p 1->name." <br> ";///When you use the unset () function to delete a private member, the __unset () method is automatically called to help us complete, remove the name private property unset ($p 1->name);//has been deleted, this line will not have output echo $p 1- >name;? >

The output is:

The Isset () function automatically calls bool (TRUE) when the private member is measured by the-is-a person name when the unset () function is used outside the class to remove the private member automatically when the __set (), __get (), __isset (), __unset () These four methods are added to the object, and are automatically called when needed to complete the operation of the object's internal private property outside the object.

The above is the PHP object-oriented Learning Tutorial 5 content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.