PHP Object-oriented encapsulation, inheritance, polymorphism of the three major features of the case

Source: Internet
Author: User
PHP Object-oriented three characteristics learning objectives: Fully understand abstraction, encapsulation, inheritance, polymorphism

Three main features of face-to-direction: encapsulation, inheritance, polymorphism first, simply understand the abstraction:
When we define a class in front of us, we actually extract the properties and behaviors common to a kind of things, and form a physical model (template), the method of studying the problem is called abstract

First, the encapsulation of
Encapsulation is the extraction of data and the operation of the data is encapsulated together, the data is protected internally, the other parts of the program only authorized operations (methods) to manipulate the data.
PHP provides three types of access control modifiers
Public indicates global, inside of this class, outside of class, subclass can access
Protected represents protected, only this class or subclass can access
Private means that only this class can be accessed internally.
The above three modifiers can be decorated with either a method or a property (variable), and if there is no access modifier, the default is public, the member property must specify an access modifier, and in PHP4 the Var $name, which means that the property is exposed and is not recommended
Cases:

<?php class person{public $name; protected $age; private $salary; function construct ($name, $age, $salary) {$this->n Ame= $name; $this->age= $age; $this->salary= $salary; The Public Function Showinfo () {///This means that three modifiers can be used inside this class using echo $this->name. $this->age. "| |". $this->salary; }} $p 1=new person (' Zhang San ', 20,3000); This belongs to the outside of the class, then if you use the following method to access the age and salary will be an error//echo $p 1->age; echo$p1->salary;?>

So what should I do now to access the elements and methods of protected and private externally? The common practice is to access these variable formats through the public function:

Public Function setxxxx ($val) {$this->xxxx= $val,} public Function getxxxx () {return $this->xxxx;}

Here with set and get just for identification convenience, not necessary
Such as:

Public Function Getsalary () {return $this->salary;//extensions: Here you can call some methods, such as determining the user name, and so on, to access}

Externally, Echo $p 1->getsalary () can be used.
If you want to access protected and private you can also use the following methods, but not recommended, as long as you understand
Set () and get ()
Set () assigns a value to the protected or private property
Set ($name, $val);
Get () Gets the value of protected or private
Get ($name);
Such as:

<?php class testa{protected $name;//Use Set () to manage all properties public function set ($pro _name, $pro _val) {//above $pro_name and $pro_ Val can be customized//under $this->pro_name for the established, non-changing $this->pro_name= $pro _val;  }//Use Get () to get all property values Public function get ($pro _name) {if (Isset ($pro _name)) {return $this->pro_name;} else {return null; }}} $n 1=new testa (); Normally, the protected property cannot be accessed outside the class, but it can be manipulated using the above method $n 1->name= ' small Three '; echo $n 1->name;?>

The above code to understand the line, not recommended to use
second, the inheritance of
Let's look at an example:

<?php class pupil{public $name, protected $age, Public function GetInfo () {echo $this->name. ' | | '. $this->age; } Public Function testing () {echo ' This is pupil ';}} Class graduate{public $name, protected $age, Public function GetInfo () {echo $this->name. ' | | '. $this->age; } Public Function testing () {echo ' This is graduate ';}} ?>

As can be seen from the above example, when multiple classes have many common properties and methods, code reusability is not high, code redundancy, thinking about the processing methods in CSS
Workaround: Inherit

<?php class students{Public $name $age Public function construct ($name, $age) {$this->name= $name; $this-&G T;age= $age; } public Function Showinfo () {echo $this->name. ' | | '. $this->age; }} class Pupil extends students{function testing () {echo ' pupil '. $this->name. ' is testing ';}} class Graduate Exten DS students{Function Testing () {echo ' graduate '. $this->name. ' is testing ';}} $stu 1=new pupil (' Zhang San ', 20); $stu 1->showinfo (); Echo ' <br/> '; $stu 1->testing ();?>

As can be seen from the above, inheritance is a subclass (subclass) that inherits the properties and methods of public and protected in the parent class (BaseClass) through the extends parent class, and cannot inherit private properties and methods
Syntax structure:
Class parent class Name {}
Class subclass name extends parent class name {}
Details:
1, a subclass can inherit only one parent class (this refers to direct inheritance); If you want to inherit the properties and methods of multiple classes, you can use multi-level inheritance
Cases:

<?php class a{Public $name = ' AAA ',} class B extends a{public $age =30;} class C extends b{} $p =new C (); Echo $p->name;//here will output AAA?>

2. When a subclass object is created, the constructor of its parent class is not automatically called by default
Cases:

Class a{Public Function construct () {echo ' A ',}} class B extends a{public function construct () {echo ' B ';}} $b =new b ()///This will give precedence to the construction method in B, if there is no construction method in B to output the

3. In subclasses, if you need to access a method of a parent class (a constructor method, a modifier for a member method method, protected or private), you can use the parent class: Either the method name or the parent:: Method name to complete "Both the parent and the previously mentioned self are lowercase, Uppercase Error "

Class a{Public Function test () {echo ' A_test ',}} class B extends a{public function construct () {//two methods All line A::test (); PA Rent::test (); }} $b =new B ();

5, if the method of a subclass (derived class) is exactly the same as the method of the parent class (public,protected), we are called method overrides or method overrides (override) to see the polymorphism below
Iii. Polymorphism
Cases:

<?php class animal{public $name, public $price, Function cry () {echo ' I don\ ' t know ';}} class Dog extends animal{// Overwrite, override function Cry () {echo ' Wang wang! '; Animal::cry ();//This will not error, can correctly execute the parent class cry (); }} $dog 1=new Dog (); $dog 1->cry ();?>

Summary:
1, when a parent class knows that all subclasses have a method, but the parent class is not sure how to write the method, you can let the subclass to overwrite its methods, method overrides (Overrides), must require the subclass of the method name and the number of parameters exactly the same
2. If the subclass is going to call a method of the parent class (Protected/public), you can use the parent class Name:: Method Name or Parent:: Method Name
3. When implementing a method override, the access modifier can be different, but the access rights of the subclass method must be greater than or equal to the access rights of the parent method (that is, access to the parent method cannot be reduced)
If the parent class public Function Cry () {} Subclass protected function Cry () {} will error
However, the access rights of subclasses can be magnified, such as:
Parent class Private Function Cry () {} Subclass protected function Cry () {} can execute correctly
Extended:
Method Overloading (overload)
Basic concept: The function name is the same, but the number of parameters or parameters of different types, to call the same function, you can distinguish between different functions
Overloading is also supported in PHP5, but it is quite different from other languages, and it is not possible to define multiple functions with the same name in PHP
PHP5 provides a powerful "magic" function, using these magic functions, we can do function overloading,
Here we go to call, when an object calls a method, and the method does not exist, the program automatically
"The service is not recommended."
There are several magic constants in PHP: Line FILE DIR FUNCTION CLASS, etc.
Cases:

<?php class a{function Test1 ($p) {echo ' test1<br/> ';} function Test2 ($p {echo ' test2<br/> ';} function call ($method, $p) {//here $p an array, above two variable names can be customized if ($method = = ' Test ') {if (count ($p) ==1) {$ This->test1 ($p); } else if (count ($p) ==2) {$this->test2 ($p);}} }} $a =new a (); $a->test (5); $a->test (3,5); 

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.