Php object-oriented programming (2), php object-oriented programming _ PHP Tutorial

Source: Internet
Author: User
Php object-oriented programming (2): php object-oriented programming. Php object-oriented programming (II). php object-oriented programming now let's take a look at an encapsulation problem of object-oriented encapsulation: in my understanding, it can be understood as a USB flash drive. php object-oriented programming (2) and php object-oriented programming

Now let's take a look at an object-oriented encapsulation problem.

Encapsulation: In my understanding, it can be understood as a USB flash disk. We use the USB flash disk interface to interact with computer data, but we cannot see the structure in it. this feature is called encapsulation.

Benefit: With this feature, we can maximize the quality of code. in other code, we only need to reference the interface and do not need to write it every time. This increases the self-sufficiency of code and reduces the difficulty of eliminating bugs.

Now let's think about a problem: my PC has a password, so I don't want anyone else to log on, copy and paste it in your computer. There is also an object like a person, the attributes of height and age, which can only be increased by oneself, and cannot be randomly assigned by others.

We use the private keyword to encapsulate the code.

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, remove var.

 Name. "Gender :". $ this-> sex. "My age is :". $ this-> age;} // this person's walking method is encapsulated by 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 occurs when an attempt is made to print a private property. echo $ p1-> name; echo $ p1-> sex; echo $ p1-> age; // An error occurred while trying to print a private member method. $ 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 ' '
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; // 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. change the code above:

 Initial value $ 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); // The following method of accessing the $ p1 object $ p1-> say (); // access the method of speaking in the $ p2 object below $ p2-> say (); // access the method of speaking in the $ p3 object below $ p3-> say ();?>

Because the constructor is the default public method (the constructor should not be set to private), if it is set to private, it is equivalent to sealing the only interface in the USB flash disk, we cannot access this class.

In the above example, we can see that private members can only be used within the class and cannot be directly accessed from outside the class. However, sometimes we need to assign values to and read private attributes, we need to provide some accessible interfaces to the outside of the class.

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 );}

Next, let's take a look at the application of the four methods _ set ,__ get ,__ isset ,__ unset

After the above explanation, we may have questions about how to operate private classes ?????

_ Set settings :__ get

 $ Property_name) {return ($ this-> $ property_name);} else {return (NULL) ;}// _ set () function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value ;}

A complete example:

 "; If (isset ($ this-> $ property_name) {return ($ this-> $ property_name);} else {return NULL ;}// _ set () this method is used to set the private property function _ set ($ property_name, $ value) {echo "this _ set () is automatically called when the private property value is directly set () the method is to assign a value to a private property.
"; $ 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 setting the private property value directly, the _ set () method is automatically called to assign values to the private property.
When setting the private property value directly, the _ set () method is automatically called to assign values to the private property.
When setting the private property value directly, the _ set () method is automatically called to assign values to the private property.
The _ get () method is automatically called when the private property value is obtained directly.
Name: James
The _ get () method is automatically called when the private property value is obtained directly.
Gender: Male
The _ get () method is automatically called when the private property value is obtained directly.
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.

If you use the "isset ()" function outside an object to determine whether the members in the object are set, can you use it? In two cases, if the members in the object are public, we can use this function to determine the member attributes. if the member attributes are private, this function does not work, the reason is that the private object is encapsulated and invisible to the outside. So 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 to the class. when using "isset ()" outside the class () "function to determine whether the private members in the object are set, the" _ isset () "method in the class will be automatically called to help us complete this operation, the "_ isset ()" method can also be made 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 );}

Complete example

 $ 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 a private member, it is automatically called.
Boolean true
This is a person name
Automatically called when the unset () function is used outside the class to delete private members
When the isset () function is used to determine a private member, it is automatically called.

Next we want to understand the inherited knowledge.

Below is the human code

// Define a "Person" class as the parent class Person {// The following is the member attribute var $ name of a Person; // The name of a Person var $ sex; // gender var $ age; // person's age // define a constructor parameter to assign values to the attribute name $ name, gender $ sex, and age $ age. function _ construct ($ name, $ sex, $ age) {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> age = $ age ;} // This person can talk about the function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age ;}}

The following is the student code.

Class Student {// The following is the member attribute var $ name of a person; // The name of a person var $ sex; // gender var $ age of a person; // age var $ school; // attributes of the school where the student is located // define a constructor parameter to assign values to the attribute name $ name, gender $ sex and age $ age _ construct ($ name = "", $ sex = "", $ age = "", $ school = "") {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> age = $ age; $ this-> school = $ school;} // The method that this person can talk to and state his own attribute function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";}// The student's learning method function study () {echo" My name is :". $ this-> name. "I am ". $ this-> school. "Learning
";}}

Simplify student categories

Class Student extends Person {var $ school; // attributes of the Student's school // function study () {echo "My name is :". $ this-> name. "I am ". $ this-> school. "Learning
";}}

Now we need to consider the problem of overloading.

At this time, you may have doubts that php does not seem to be reloaded, because PHP is a language-specific method. in the traditional sense, there are multiple methods with the same name, however, parameters with different numbers are used to call different interfaces.

The overload I am talking about is a subclass that overwrites the parent class.

 Name = $ name; $ this-> sex = $ sex; $ this-> age = $ age;} // The way this person can speak, say your own property function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age ;}} class Student extends Person {var $ school; // attributes of the Student's school // function study () {echo "My name is :". $ this-> name. "I am ". $ this-> school. "Learning";} // this learning method that can be used to speak out all its attributes. it covers the function say () {echo of the same name method of the parent class. "my sub-names are: ". $ this-> name. "Gender :". $ t His-> sex. "My age is:". $ this-> age. "I am at". $ this-> school. "" ;}}?>

In this way, the main points of this method are:

1. Subclass must inherit the parent class

2. the method name of the subclass must be the same as that of the parent class.

At this time, we may find that if there are 1000 pieces of code in this method, it is inconvenient to implement it.

In this case, we use the "parent: method name" method to call the method that is overwritten in the parent class;

Class Student extends Person {var $ school; // attributes of the Student's school // function study () {echo "My name is :". $ this-> name. "I am ". $ this-> school. "Learning";} // this learning method that can be used to speak out all its attributes, covering the function say () method of the same name of the parent class () {// use the "class name:" of the parent class to call the override method in the parent class; // Person: say (); // or use "parent :: "To call the method to be overwritten in the parent class; parent: say (); // add your own function echo" My age is :". $ this-> age. "I am ". $ this-> school. "School ";}}

Differences between public, private, and protected

 MyPublic();$this->MyProtected();$this->MyPrivate();}}$myclass = new MyClass;$myclass->MyPublic();// Works$myclass->MyProtected();// Fatal Error$myclass->MyPrivate();// Fatal Error$myclass->Foo();// Public, Protected and Private work/** * Define MyClass2 */class MyClass2 extends MyClass{// This is publicfunction Foo2(){$this->MyPublic();$this->MyProtected();$this->MyPrivate();// Fatal Error}}$myclass2 = new MyClass2;$myclass2->MyPublic();// Works$myclass2->Foo2();// Public and Protected work, not Private?>

The above code can be summarized as follows:

Public: external access is allowed.

The indirect external access of protected requires an interface like a USB flash drive and a computer, and that interface requires a subclass (the subclass inherits the protected of the parent class)

Private cannot be accessed from outside

Now that we are talking about inheritanceIf we want a class not to be inherited, we can use final to define it (only classes and methods can be defined, but member attributes cannot be defined)

1. the class marked by final cannot be inherited

2. methods marked by final cannot be overwritten by the quilt class.

 

  

The following error occurs:

Fatal error: Class Student may not inherit from final class (Person)
 

Understand the use of key keywords of static and const (self :)

Static literally means static. now you may ask what are the advantages of static usage? The advantage of static usage is that if there is a common property in the object of thousands of "people", such as the nationality "China", then we can set the property of nationality to static, there is a location in the memory. during The instantiation process, thousands of people will access this location in the memory.

Static members can restrict external access. Because static members belong to classes and do not belong to any object instance, they are allocated space when the class is loaded for the first time, other classes cannot be accessed. they only share instances of the class and can protect the members of the class to a certain extent;

This is a bit like a global variable in the website.

 

The result is:

China, I am a chinese, United States

It can also be written in this way.

 ShowConstant (); // echo $ class: constant; // is not allowed?>

The access method of the member attribute modified with "const" is similar to that of the member access modified with "static". The "class name" is also used, and the "self" keyword is used in the method. However, you do not need to use the "$" symbol or use an object for access.

 ShowConstant (); // echo $ class: constant; // is not allowed?>

  

Objective (2), php object-oriented programming now let's take a look at an encapsulation problem of object-oriented encapsulation: In my understanding, we can be understood as a USB flash drive...

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.