PHP basic tutorial 11: encapsulation, inheritance, and polymorphism

Source: Internet
Author: User
This section describes how to encapsulate and inherit multi-state rewriting.

Content described in this section
  • Encapsulation

  • Inheritance

  • Polymorphism

  • Heavy load

  • Rewrite

Preface

Like JAVA object-oriented, PHP has three main features: encapsulation, inheritance, and polymorphism. These three features optimize the object-oriented architecture in many aspects. These three features also need to be considered during the development of object-oriented.

Encapsulation

What is encapsulation in object orientation?

Encapsulation: encapsulates abstract data and operations on data, and the data is protected internally. other parts of the program are only authorized operations (member methods ), to operate the data.

Abstraction is mentioned above, that is, extracting the common attributes and behaviors (methods) of a class of things to form a template (class). This method of studying the problem is called abstraction.

Just like our bank account, no matter who the account is, it includes the account and password. it also has some common methods, such as withdrawal, deposit, and balance inquiry. The encapsulated idea is:

 Account_no = $ account_no; $ this-> pwd = $ pwd; $ this-> balance = $ balance;} // deposit public function deposit ($ amount, $ pwd) {if ($ pwd = $ this-> pwd) {echo'
Deposit successful '; $ this-> balance + = $ amount;} else {echo'
Incorrect password ';}}// withdrawal public function withdraw ($ amount, $ pwd) {if ($ pwd ==$ this-> pwd) {if ($ this-> balance >=$ amount) {echo'
Withdrawal successful '; $ this-> balance-= $ amount;} else {echo'
Insufficient balance... ';}} else {echo'
Incorrect password ';}} // query public function query ($ pwd) {if ($ pwd ==$ this-> pwd) {echo'
Account '. $ this-> account_no.' balance = '. $ this-> balance;} else {echo'
Query password error ';}}$ account = new Account (123456789, 'heat123', 2000000); $ account-> deposit (30000, 'heat123 '); $ account-> query ('heat 123'); $ account-> withdraw (99999900, 'heat 123'); $ account-> query ('heat 123 ');

The above code is the encapsulation of the banking business, through the encapsulation code. We only need to call the method provided in the operation, instead of managing how the business is handled. This is an important idea. The encapsulation method is to use the access modifier and use the access characteristics of the access modifier to encapsulate the attributes or methods that are not used externally. In the previous section, we talked about three access modifiers.
So how can we access the protected and private member attributes? There are three methods.

First

Use Magic methods _ get () and _ set () to access

 Name = $ name; $ this-> age = $ age;} public function _ set ($ name, $ value) {// check whether the class has this attribute if (property_exists ($ this, $ name) {$ this-> $ name = $ value ;} else {echo 'does not have this attribute';} public function _ get ($ name) {return $ this-> $ name ;}} $ cat = new Cat ('xiaobai', 2); $ cat-> name = 'floret '; echo $ cat-> name ;...... result ...... xiaohua

We use the magic set and get methods to change the value of protected attributes, but this method is not recommended. Because it is not flexible enough, the incoming data cannot be verified. The following method can verify the passed data.

Second

Provides a pair of getXxx () and setXxx () methods for each private or protected member variable.

 Name = $ name; $ this-> age = $ age;} public function setName ($ value) {if (is_string ($ value )) {$ this-> name = $ value;} public function getName ($ password) {if ('000000' = $ password) {return $ this-> name ;} else {echo 'wrong password ';}}$ cat = new Cat ('xiaobai', 2); $ cat-> setName ('flag '); echo $ cat-> getName ('20140901 ');...... result ...... xiaohua

This method can be used to determine the data passed in. We recommend this method.

Third

Use a unified method to operate attributes.

 Name = $ name; $ this-> age = $ age;} // display the object information public function showInfo () {echo $ this-> name. 'age :'. $ this-> age ;}}$ cat = new Cat ('xiaobai', 2); $ cat-> showInfo ();...... result ...... the age of Tom is: 2

These three methods are used in the second and third methods during development. when you operate on a single attribute, you can use the second method, when you operate on multiple attributes, you can use the third type.

Inheritance

Inheritance is often used in development, which reduces code redundancy. The code looks clearer. So what is inheritance?

 Name = $ name; $ this-> age = $ age;} public function showInfo () {echo'
Student Information: '; echo'
Student name: '. $ this-> name; echo'
The student's score is :'. $ this-> grade;} // set the score public function setGrade ($ grade) {$ this-> grade = $ grade;} public function testing () {echo'
Pupils are taking the exam ......... ';}} // defines a college student. it has the test method and sets the score method class Graduate {public $ name; public $ age; private $ grade; public function _ construct ($ name, $ age) {$ this-> name = $ name; $ this-> age = $ age;} public function showInfo () {echo'
Student Information: '; echo'
Student name: '. $ this-> name; echo'
The student's score is :'. $ this-> grade;} // set the score public function setGrade ($ grade) {$ this-> grade = $ grade;} public function testing () {echo'
College students are taking the exam ..... ';}} // use $ pupil1 = new Pupil ('xiaoming', 40); $ pupil1-> testing (); $ pupil1-> setGrade (100 ); $ pupil1-> showInfo (); echo'
'; // Use $ graduate1 = new Graduate ('Hua', 20); $ graduate1-> testing (); $ graduate1-> setGrade (60 ); $ graduate1-> showInfo ();

In the above code, we can see that both classes have the same attributes and methods. if our code contains many such code, code redundancy will occur, which is not conducive to our maintenance. The best solution is to use inheritance to improve code reuse.

Inherited syntax:

Class method name extends parent class method name {}

Inherit using keywordsExtends. It can be understood that code reuse makes programming closer to human thinking. when multiple classes have the same attributes (variables) and methods, you can extract the parent class from these classes and define these identical attributes and methods in the parent class. all subclasses do not need to redefine these attributes and methods, you only need to inherit the parent class.

 Name = $ name; $ this-> age = $ age;} public function showInfo () {echo'
Student Information: '; echo'
Student name: '. $ this-> name; echo'
The student's score is :'. $ this-> grade;} // set the score public function setGrade ($ grade) {$ this-> grade = $ grade ;}} // Here The extends keyword indicates that the Pupil class inherits the Student class Pupil extends Student {public function testing () {echo'
Pupils are taking the exam... ';}} class Graduate extends Student {public function testing () {echo'
College students are taking the exam ......... ';}}$ pupil1 = new Pupil ('xiaoming', 40); $ pupil1-> testing (); $ pupil1-> setGrade (100 ); $ pupil1-> showInfo (); echo'
'; $ Graduate1 = new Graduate ('huahua', 20); $ graduate1-> testing (); $ graduate1-> setGrade (60); $ graduate1-> showInfo ();

The code above shows that the same attributes and methods are all included in the Student class (parent class). we will write two classes to inherit the parent class through the extends keyword.
The class used for inheritance is called the parent class, and the class that inherits this class is called the subclass.
As long as inheritance is passed, we can use the attributes and methods in the parent class. However, ifIf the property or method is private, the subclass cannot inheritThis is the difference between protected and private.

If the subclass obtains the attributes and methods of the parent class through inheritance, does it assume that the code of the parent class has been assigned a copy to the subclass? Actually not. Inheritance not simply copies the attributes and method definitions of the parent class to the subclass, but establishes a search relationship. When we try again, the search relationship is:

  1. When an object operates on attributes and methods, it first checks whether there are corresponding attributes and methods in this class. if so, it determines whether there is access permission. if so, it accesses the object, if the access is unavailable, an error is returned.

  2. When an object operates on attributes and methods, it first checks whether there are corresponding attributes and methods in this class. if not, it searches for its parent class. its parent class has, determine whether access is allowed. if access is allowed, an error is returned if access is not allowed.

  3. The search logic goes to the top-level class .....

There are still many notes in inheritance:

  • A subclass can inherit only one parent class (direct inheritance), which is different from c ++.

  • Subclass can inherit the public, protected modified variables (attributes) and functions (methods) of its parent class (or base class)

  • When a subclass object is created, the constructor of its parent class is automatically called by default (when the subclass does not have a custom constructor)

       
  • If you need to access the method of the parent class in the subclass (the access modifier of the constructor/member method is public/protected), you can use the parent class: method name (or parent :: method name) to complete

       ';}} Class B extends A {// subclass defines its own constructor and does not call the constructor of the parent class. Public function _ construct () {parent ::__ construct (); echo 'constructor of the subclass
    ';}} // If no constructor is defined for the subclass, the constructor of the parent class is executed. $ B = new B (); ...... result ...... constructor of the constructor subclass of the parent class
  • If the method in the subclass is the same as that in the parent class, it is called method rewriting.

Polymorphism

In general, Polymorphism refers to multiple forms, that is, in object orientation, multiple states of objects under different circumstances (based on the context used) PHP is inherently a multi-state language, at the same time, PHP can call the corresponding object method based on different input object types.

In PHP, variable definitions are not similar to the types defined before variable names in other languages. Instead, they are defined using the $ symbol and can accept values of any type. This creates conditions for polymorphism. Depending on the type of the input object, call the method of the corresponding object. we can also use the type constraint to constrain the input value.

Type constraints

The basic concept of type constraints is that PHP 5 can use type constraints. Function parameters can be specified as objects (specify the class name in the function prototype), interfaces, arrays (from PHP 5.1) or callable (from PHP 5.4 ). For example, PHP only supports these types.

 ';} // The parameter is the array public function test_array (array $ arr) {print_r ($ arr) ;}} class Cat {}$ cat = new Cat (); $ myClass = new MyClass (); $ arr = array (1, 2, 4, 5); $ myClass-> test ($ cat ); $ myClass-> test_array ($ arr );..... result ...... object Array ([0] => 1 [1] => 2 [2] => 4 [3] => 5)

If you want to apply a type constraint, just write the type before the parameter. you can try the Input type that is not the constraint and a fatal error will be reported.

Example of polymorphism:

 Name = $ name ;}// Cat class Cat extends Anmial {public function showInfo () {echo'
The cat name is '. $ this-> name ;}// Dog class Dog extends Anmial {public function showInfo () {echo'
The dog name is '. $ this-> name ;}// Monkey class Monkey extends Anmial {public function showInfo () {echo'
The monkey name is '. $ this-> name ;}// define the class Food {public $ name; public function _ construct ($ name) {$ this-> name = $ name ;}} class Fish extends Food {public function showInfo () {echo'
'. $ This-> name ;}} class Bone extends Food {public function showInfo () {echo'
'. $ This-> name ;}} class Peach extends Food {public function showInfo () {echo'
'. $ This-> name ;}// Master of the primary human class {public $ name; public function _ construct ($ name) {$ this-> name = $ name ;} // The owner can feed. // when our type constraint is a parent class, the owner can accept its subclass object instance public function feed (Anmial $ aniaml, Food $ food) {echo'
Host '. $ this-> name; $ aniaml-> showInfo (); // use polymorphism to call different methods based on input values. Echo'
The Fed food is '; $ food-> showInfo () ;}}$ dog = new Dog ('yellow dog'); $ cat = new Cat ('cat '); $ monkey = new Monkey ('Monkey '); $ fish = new Fish ('Shark'); $ bone = new Bone ('bone '); $ peach = new Peach ('peach '); $ master = new Master ('xiaoming'); $ master-> feed ($ dog, $ bone); echo'

'; $ Master-> feed ($ cat, $ fish); echo'

'; $ Master-> feed ($ monkey, $ peach );

In the feeding method of the master, the above code uses type constraints to call methods of different objects based on different objects passed in.

Heavy load Method overloading

Overload: simply put, a function or method has the same name but different parameter lists. such functions or methods with different parameters of the same name are called overload functions or methods.

The method overload mentioned above can be understood as there are two functions with the same method name in a class, but the function parameters are different. when we call the function, the system automatically calls different functions based on the input parameters. this is an overload, but a class in PHP cannot have two functions with the same method name, although your parameters are different, it will report a Cannot redeclare error. So it cannot be reloaded in PHP? Actually, you can use magic methods.

In the previous section, we introduced a magic method that is automatically called by the system when we access an inaccessible or nonexistent method, that is, the _ call () method. PHP can be overloaded using this magic method

 Add1 ($ val_arr [0], $ val_arr [1]);} else if ($ num = 3) {return $ this-> add ($ val_arr [0], $ val_arr [1], $ val_arr [2]) ;}}$ calculate = new Calculate (); echo $ calculate-> add (1, 2); echo'
'; Echo $ calculate-> add (1, 2, 3); ...... result ...... 3 6

To check whether the code is spoofed, first set the two methods in the class to private, so that they cannot be accessed outside the class. when we access the add method outside the class, the magic method is called, and the number of parameters is determined by the number of input arrays, so that the appropriate method is removed from the magic method. This is the PHP method overload.

Attribute overloading

In PHP object-oriented programming, when you assign a value to a non-existent property, PHP creates a corresponding property named "dynamic" by default.

 '; Var_dump ($ a); $ a-> age = 12; var_dump ($ );..... result ...... object (A) #1 (1) {["name"] => string (6) "Xiaoming"} object (A) #1 (2) {["name"] => string (6) "Xiaoming" ["age"] => int (12 )}

As you can see from the results, when we assign a value to a non-existent property age, the property age appears in the output class structure, which is the overload of the property.

If you do not want the class attributes to be automatically added, you can use the magic methods _ set () and _ get () to control them.

Rewrite Method rewriting

We have introduced the object-oriented inheritance mechanism above. Rewriting is based on inheritance. When a class inherits from another class, there is a method in the parent class, and the subclass inherits, but in the subclass, the method of the parent class does not meet the requirements, A subclass needs to re-define a method that is the same as the method of the parent class during rewriting, which is called rewriting. To put it bluntly, a subclass has a method, which has the same name and number of parameters as a method of the parent class (base class.

 ';}} Class Cat extends Animal {// override the public function eat () {echo 'cat is eating
';}}$ Cat = new Cat (); $ cat-> eat ();... result... cat is eating

If the type constraint is used in the method of the parent class, the type constraint of the child class must be the same.

In method rewriting:

  1. Number of parameters of the subclass method, method name, which must be the same as the number of parameters of the parent method.

  2. Subclass methods cannot reduce the access permission of the parent method (which can be greater than or equal)

Note: If the method name of the parent class is private, the subclass will not be overwritten.

Overwrite attributes

Public and protected attributes can be overwritten, while private attributes cannot be overwritten.

 '; Var_dump ($ cat );...... result ...... object (Cat) #1 (4) {["name"] => string (6) "" ["age": protected] => int (4) ["sex": "Cat": private] => string (3) "xiong" ["sex": "Animal": private] => string (3) "Xiong "}

We can see that the name and age are rewritten, and the private cannot be rewritten.

Summary

In object-oriented systems, encapsulation is a very important idea. the implementation of encapsulation can reduce the code coupling and reduce code redundancy during inheritance, the unique language structure of php also shines on polymorphism, and the mastery of rewriting gives us a deeper understanding of inheritance. (Ps: Today's 10.1, the birthday of the motherland, I am going to celebrate the birth of the motherland's mother)

The above is the encapsulation, inheritance, and polymorphism of the PHP basic tutorial 11. For more information, see PHP Chinese website (www.php1.cn )!

Related Article

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.