PHP Basic Tutorial 11 encapsulation, inheritance, polymorphism

Source: Internet
Author: User
Tags ming modifiers php class

What this section explains

    • Packaging

    • Inherited

    • Polymorphic

    • Overload

    • Rewrite

Objective

PHP's object-oriented and Java-oriented object, are divided into three characteristics, encapsulation, inheritance, polymorphism. These three features are optimized for many aspects of object-oriented. These three characteristics are also issues that need to be considered when developing object-oriented.

Packaging

What is encapsulation in object-oriented?

Encapsulation: The abstraction of the data and the operation of the data is encapsulated together, the data is protected inside, the other parts of the program only through the authorized operation (member method), the data can be manipulated.

The above mentioned abstraction, that is, to extract a class of common properties and behaviors (methods), to form a template (Class), this method of research problems, we call abstraction.

Like our bank account number, regardless of who's account, including account number, password, but also have some common methods, withdrawals, deposits, check the balance. The idea that we use encapsulation is:

<?php class account{public $account _no;        Private $pwd;        Private $balance;            Public function __construct ($account _no, $pwd = ' 123456 ', $balance = 0.0) {$this->account_no = $account _no;            $this->pwd = $pwd;        $this->balance = $balance; }//Deposit Public Function deposit ($amount, $pwd) {if ($pwd = = $this->pwd) {echo ' &L                T;br> deposit Success ';            $this->balance + = $amount;            }else{Echo ' <br> password incorrect ';                }}//Withdrawal public function withdraw ($amount, $pwd) {if ($pwd = = $this->pwd) {                    if ($this->balance >= $amount) {echo ' <br> withdrawal success ';                $this->balance-= $amount;                }else{Echo ' <br> insufficient balance: ';            }}else{echo ' <br> password error '; }}//Query PublIC function Query ($PWD) {if ($pwd = = $this->pwd) {echo ' <br> account '. $this->account_no . ' Balance = '.            $this->balance;            }else{echo ' <br> query password error ';    }}} $account = new account (123456789, ' hsp123 ', 2000000);    $account->deposit (30000, ' hsp123 ');    $account->query (' hsp123 ');    $account->withdraw (99999900, ' hsp123 '); $account->query (' hsp123 ');

The code above is the encapsulation of the banking business, by encapsulating the code. We only need to invoke the method provided inside, instead of managing how the business is handled. This is an important thought. The way we implement encapsulation is to use the access modifiers, which take advantage of access modifiers, to encapsulate properties or methods that are not externally used. In the previous section, we talked about three access modifiers.
So how do we access protected and private member properties? There are three ways to do this.

First Kind

Use the Magic Method __get () and __set () to access

<?php    class cat{        private $name;        Private $age;        Public function __construct ($name, $age) {            $this, name = $name;            $this, age = $age;        }        Public Function __set ($name, $value) {            //determine if the class has this property            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 (' Small white ', 2);    $cat, name = ' Floret ';    Echo $cat, name;    ...... The result ...    Small flower

We use the Magic method set and Get properties to change the value of the protected property, but this method is not recommended. Because it is not flexible enough, it is not possible to validate incoming data. The following method can be used to verify the incoming data.

The second Kind

A pair of getxxx () and Setxxx () methods are provided for each private or protected member variable.

<?php    class cat{        private $name;        Private $age;        Public function __construct ($name, $age) {            $this, name = $name;            $this, age = $age;        }        Public Function SetName ($value) {            if (is_string ($value)) {                $this, name = $value;            }        }        Public Function GetName ($password) {            if (' 12345 ' = = $password) {                return $this, name;            } else{                echo ' wrong password ';            }        }    }    $cat = new Cat (' Small white ', 2);    $cat-SetName (' Floret ');    Echo $cat-getName (' 12345 ');    ...... The result ...    Small flower

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

Third Kind

Use a uniform method to manipulate the properties.

<?php    class cat{        private $name;        Private $age;        Public function __construct ($name, $age) {            $this, name = $name;            $this, age = $age;        }        Displays information about the object public        function Showinfo () {            echo $this, name. ' The Age is: '. $this-age;        }    }    $cat = new Cat (' Small white ', 2);    $cat-Showinfo ();    ...... The result ...    The age of Small white is: 2

These three methods, we in the development of the second and third use more, when the single attribute operation, you can use the second, when the operation of a variety of properties, you can use the third.

Inherited

There are too many uses of inheritance in development, and the occurrence of inheritance reduces the redundancy of the code. Is that the code looks more clear. So what is inheritance?

<?php//Define a pupil, it has the method of examination, the method of setting the result class pupil {public $name;        Public $age;        Private $grade;            Public function __construct ($name, $age) {$this->name = $name;        $this->age = $age;            } public Function Showinfo () {echo ' <br> students ' information is as follows: '; Echo ' <br> Student's name is: '.            $this->name; Echo ' <br> students ' results are: '.        $this->grade;        }//Set the result public function Setgrade ($grade) {$this->grade = $grade;        } Public Function testing () {echo ' <br> pupil in exam ... ';        }}//define a college student, it has the method of examination, the method of setting the result class Graduate {public $name;        Public $age;        Private $grade;            Public function __construct ($name, $age) {$this->name = $name;        $this->age = $age;            } public Function Showinfo () {echo ' <br> students ' information is as follows: '; Echo ' <br> Student's name is: '. $this->name; Echo ' <br> students ' results are: '.        $this->grade;        }//Set the result public function Setgrade ($grade) {$this->grade = $grade;        } Public Function testing () {echo ' <br> college students in exams ...;    }}//use $pupil 1 = new pupil (' Xiao Ming ', 40);    $pupil 1->testing ();    $pupil 1->setgrade (100);    $pupil 1->showinfo ();    Echo ' <br> ';    Use $graduate 1 = new graduate (' Xiao Hua ', 20);    $graduate 1->testing ();    $graduate 1->setgrade (60); $graduate 1->showinfo ();

In the above code, we can see that two classes have the same properties and methods, if our code has a lot of such code, it will cause the code redundancy, more detrimental to our maintenance. The best way to solve this problem is to use inheritance to improve the reusability of the code.

Inherited syntax:

class method name extends the method name of the parent class {}

Inheritance is inherited using the keyword extends . Can be understood as code reuse, let our programming closer to human thinking, when more than one class has the same attributes (variables) and methods, you can extract the parent class from these classes, in the parent class to define the same properties and methods, all subclasses do not need to redefine these properties and methods, just inherit the parent class is OK

<?php//Use inheritance to complete class student{public $name;        Public $age;        Private $grade;            Public function __construct ($name, $age) {$this->name = $name;        $this->age = $age;            } public Function Showinfo () {echo ' <br> students ' information is as follows: '; Echo ' <br> Student's name is: '.            $this->name; Echo ' <br> students ' results are: '.        $this->grade;        }//Set the result public function Setgrade ($grade) {$this->grade = $grade;            }}//Here The Extends keyword means that the pupil class inherits Student class pupil extends student{public Function testing () {        Echo ' <br> pupils in exams ... ';        }} class Graduate extends student{public Function testing () {echo ' <br> college students in exams ... ';    }} $pupil 1 = new pupil (' Xiao Ming ', 40);    $pupil 1->testing ();    $pupil 1->setgrade (100);    $pupil 1->showinfo ();    Echo ' <br> '; $graduate 1 = new graduate (' smallChina ', 20);    $graduate 1->testing ();    $graduate 1->setgrade (60); $graduate 1->showinfo ();

You can see that the same properties and methods go out to the student class (the parent Class) in the code above, and we write two more classes to inherit the parent class through the extends keyword.
The class to inherit is called the parent class, and the class that inherits it is called a subclass.
As long as we inherit, we can use the properties and methods inside the parent class. However, if the parent class's properties or methods are modified by private, the subclass cannot inherit , which is the difference between protected and private.

Subclasses inherit the properties and methods of the parent class, do you think the code of the parent class is assigned a copy to the subclass? Actually, it's not. Inheritance is not simply a copy of the parent class's property and method definition to the subclass, but a lookup relationship is established. And when we revisit, this lookup relationship is:

    1. When an object to manipulate properties and methods, first in this class to see whether there are corresponding properties and methods, if there is, to determine if there is access, if you can access the access, if you can not access the error

    2. When an object to manipulate properties and methods, first in this class to see whether there are corresponding properties and methods, if not, will go to find their own parent class, the parent class has, and then determine whether it can access, access to access, can not access the error.

    3. This lookup is logical to the top class .....

There are still a lot of things to be aware of in succession:

  • Subclasses can inherit at most one parent class (meaning direct inheritance), which is not the same as C + +.

  • Subclasses can inherit the public of their parent class (or base class), Protected modified variables (attributes) and functions (methods)

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

    <?php    class a{public        function __construct () {            echo ' the constructor of the parent class ';        }    }    Class B extends a{    }    //subclass does not have a constructor defined, it executes the constructor of the parent class.    $b = new B ();    ..... The result ...    The constructor of the parent class
  • If you need to access a method of its parent class in a subclass (the access modifier for a constructor/member method method is public/protected), you can use the parent class:: Method Name (or Parent:: Method Name) to complete the

    <?php    class a{public        function __construct () {            echo ' parent class constructor <br> ';        }    }    Class B extends a{        //subclasses define their own constructors and do not invoke the constructor of the parent class. Public        function __construct () {            parent::__construct ();            Echo ' subclass constructor <br> ';        }    }    When a subclass does not have a constructor defined, it executes the constructor of the parent class.    $b = new B ();    ..... The result ...    constructor of the parent class's constructor    subclass
  • If the methods in the subclass are the same as the parent class methods, we are called method overrides.

Polymorphic

Multi-State popular speaking is a variety of forms, that is, in object-oriented, the object in different situations of various states (according to the context of use) PHP is inherently polymorphic language, and PHP can be based on the type of object passed in, the method of invoking the corresponding object

In PHP, the definition of a variable does not define a type as in other languages before the variable name, but is defined directly with the $ symbol and can accept any type of value. This creates the conditions for polymorphism. Depending on the type of object passed in, the method of the corresponding object is called, and we can use the type constraint to constrain the passed-in value.

Type constraints

The basic concept of type constraints is that PHP 5 can use type constraints. The parameters of the function can specify that the object must be (the name of the class specified in the function prototype), interface, Array (PHP 5.1), or callable (PHP 5.4). such as the previous PHP only support these kinds.

<?php    class  MyClass    {         //passed in parameter constrained to cat or cat's subclass public               function  Test (cat $cat) {            echo ' Object <br> ';        }        The parameter is an 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);    ..... The result ...    Object    Array ([0] = 1 [1] = 2 [2] = 4 [3] = 5)

If you want to type constraints, write the type on the front of the parameter, you can try to pass in a type that is not a constraint, and will report a fatal error.

Examples of polymorphism:

<?php//polymorphic case//definition of the animal's parent class anmial{public $name;        Public function __construct ($name) {$this->name = $name; }}//Cat class Cat extends anmial{public Function showinfo () {echo ' <br> cat name is '. $this-        >name; }}//Dog class Dog extends anmial{public Function showinfo () {echo ' <br> dog name is '. $this-&        Gt;name; }}//Monkey class Monkey extends anmial{public Function showinfo () {echo ' <br> monkey name is '. $t        his->name;        }}//define the Thing class food{public $name;        Public function __construct ($name) {$this->name = $name;        }} class Fish extends food{public Function showinfo () {echo ' <br> '. $this->name;        }} class Bone extends food{public Function showinfo () {echo ' <br> '. $this->name; }} class Peach extends food{       Public Function Showinfo () {echo ' <br> '. $this->name;        }}//Master Human class master{public $name;        Public function __construct ($name) {$this->name = $name;            }//Master can feed//when our type constraint is a parent class, you can accept object instances of his subclasses public function feeds (anmial $aniaml, food $food) { Echo ' <br> master '.            $this->name; $aniaml->showinfo ();            Using polymorphism, different methods are called depending on the value passed in.            Echo ' <br> fed food is ';        $food->showinfo ();    }} $dog = new dog (' Yellow Dog ');    $cat = new Cat (' tabby 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 ' <br><br> ';    $master->feed ($cat, $fish);    Echo ' <br><br> '; $master->feed ($monkey, $peach);

The above code, in the owner's feeding method, uses type constraints, depending on the object passed in, the method of invoking different objects.

Overload

Overloading of methods

Overloading: Simply put, the function or method has the same name, but the argument list is not the same case, such a different parameter of the same name between the functions or methods, called each other overloaded functions or methods.

The above-mentioned overload of the method can be understood as in a class, there are two method names of the same functions, but the parameters of the function is not the same, when we call, the system will be based on the parameters we passed, and automatically call different functions, which is overloaded, In PHP, however, you cannot have two functions with the same method name in a class, and it will report a cannot redeclare error, even if your arguments are different. So you can't overload it in PHP? Actually, you can use the Magic method.

One way to describe the magic method in the previous section is when we access an inaccessible or nonexistent method, the system automatically calls the __call () method. This magic method can be used in PHP to overload

<?php    class calculate{        //Define two methods, calculate addition, note that the method name of two methods is not the same as the        private function add ($a, $b, $c) {             return $a + $b + $c;        }        Private function Add1 ($a, $b) {            return $a + $b;        }        Public Function __call ($name, $val _arr) {            if ($name = = ' Add ') {                //Get the parameters inside the array, determine several parameters                $num = count ($val _arr);                if ($num = = 2) {                    return $this, 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;    Echo ' <br> ';    echo $calculate Add (+/-);    ..... The result ...    3    6

See the code is not deceived feeling-_-, first set the class of two methods to private, so that outside the class can not access, when we access the Add method outside the class, will call the Magic method, and then through the number of incoming array, determine the number of parameters, so in the Magic method to remove the appropriate method. This is the PHP method overload.

Overloading of properties

In PHP object-oriented programming, when you assign a value to a nonexistent property, PHP defaults to ' dynamic ' and creates a corresponding property, which is called a property overload.

<?php    class a{        //Only one variable is defined in the class public        $name = ' xiaoming ';    }    $a = new A ();    Echo ' <pre> ';    Var_dump ($a);    $a, age = N;    Var_dump ($a);    ..... The result ...    Object (a) #1 (1) {      ["name"]=>      string (6) "Xiaoming"    }    Object (a) #1 (2) {      ["name"]=>      String (6) "Xiaoming"      ["Age"]=>      int ()    }

As you can see from the results, when we assign a value to an age that does not exist, there is an attribute in the output class structure, which is the overload of the property.

If you do not want the properties of your class to increase automatically, you can use the Magic Method __set () and the __get () method for control.

Rewrite

Override of Method

In the above we introduce the object-oriented inheritance mechanism. Rewriting is a concept that is initiated based on inheritance. When a class inherits from another class, there is a method in the parent class that inherits the subclass, but in the subclass it is considered that the method of the parent class does not satisfy the requirement, and the subclass is required to redefine the same method that defines a method of the parent class, called rewriting. To be blunt, there is a method for a subclass that has the same name and number of arguments as a method of a parent class (the base class).

<?php    class animal{        //Animals eat This behavior, specifically to see what animal public        function eat () {            echo ' eat <br> ';        }    }    class Cat extends animal{        //Overriding the method of the parent class public        function Eat () {            echo ' cat at dinner <br> ';        }           }    $cat = new Cat ();    $cat-Eat ();    ..... The result ...    The cat is eating.

If a type constraint is used in a method of a parent class, then the subclass must have the same type constraint.

In the override of the method:

    1. The number of parameters of the method of the subclass, the method name, and the number of arguments to the parent method, as well as the method name

    2. Subclass methods cannot narrow the access rights of the parent method (can be greater than can be equal)

Note: If the method name of the parent class is private, the subclass is not overridden.

Override of property

For property overrides also, public and protected can be overridden, private properties cannot be overridden

<?php    class animal{public        $name = ' floret ';        protected $age = N;        Private $sex = ' male ';    }    Class Cat extends animal{public        $name = ' small white ';        protected $age = 4;        Private $sex = ' male ';    }    $cat = new Cat ();    Echo ' <pre> ';    Var_dump ($cat);    ...... The result ...    Object (Cat) #1 (4) {      ["name"]=>      string (6) "Small white"      ["Age":p rotected]=>      Int (4)      ["Sex": " Cat ":p rivate]=>      string (3)" Male "      [" Sex ":" Animal ":p rivate]=>      string (3)" Male "    }

You can see that name and age are overridden and private cannot be overridden.

Summarize

Object-oriented, encapsulation is a very important idea, the implementation of encapsulation, can reduce the coupling degree of code, while inheriting the time to reduce the redundancy of the Code, PHP's unique language structure let polymorphic also emit light, and rewrite the mastery, let us have a deeper understanding of inheritance. (PS: Today, number 10.1th, the motherland's birthday, I will go to the motherland to celebrate the mother's Day)

The above is the PHP Basic Tutorial 11 package, inheritance, polymorphic 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.