Comprehensively analyzes the three features of PHP object-oriented, and comprehensively analyzes object-oriented

Source: Internet
Author: User

Comprehensively analyzes the three features of PHP object-oriented, and comprehensively analyzes object-oriented

PHP object-oriented features: inheritance, encapsulation, and Polymorphism

1. Inheritance

1. How to Implement inheritance?

Use the extends keyword for the subclass to inherit the parent class;

Class Student extends Person {}

2. What are precautions for inheritance?

① Subclass can only inherit non-private attributes of the parent class.

② After the subclass inherits the parent class, it is equivalent to copying the attributes and methods of the parent class to the subclass and can be called directly using $ this.

③ PHP can only inherit from one class, but cannot inherit from multiple classes. However, a class carries out multi-layer inheritance;

Class Person {} class Chengnian extends Person {} class Student extends Chengnian {} // Student class has the attributes and methods of both the Chengnian class and the Person class.

3. Method override)

Condition ① subclass inherits the parent class.

Condition ② subclass overrides existing methods of the parent class.

The method overwrites the preceding two conditions. After overwriting, The subclass calls the method and calls its own method.

In addition to method override, subclass can also have attributes with the same name as the parent class to overwrite the attributes.

4. If the subclass overrides the parent class method, how does one call the method with the same name as the parent class in the subclass?

Partent: Method Name ();

Therefore, when the subclass inherits the parent class, the first step in the subclass construction is to call the parent class construction for copying.

  function __construct($name,$sex,$school){    parent::__construct($name,$sex);    $this->school = $school;  }

One instance:

Class Student extends Person {// subclass inherits the parent class public $ school; function _ construct ($ name, $ sex, $ school) {// subclass constructor parent :: __construct ($ name, $ sex); // call the parent class structure to copy $ this-> school = $ school;} function program () {echo "PHP is really fun! I love PHP! PHP is the best programming language in the world! <Br> ";} function say () {parent: say (); // override the Same Name method of the parent class echo "I am from {$ this-> school}" ;}}$ zhangsan = new Student ("Zhang San", "male ", "Sail"); $ zhangsan-> say (); $ zhangsan-> program ();

Ii. Encapsulation

1. What is encapsulation?

The access modifier is used to privatize the attributes and methods that do not require external access in the class to implement access control.

Note ]:Is to implement access control, rather than deny access. That is to say, after we privatize the attributes, we need to provide corresponding methods for users to process the attributes through the methods we provide.

2. What is the role of encapsulation?

① The user only cares about the functions that the class can provide, rather than the details of the function implementation! (Encapsulation method)

② Control user data to prevent illegal data setting and control the data returned to the user (attribute encapsulation + set/get method)

3. How to Implement encapsulation?

① Encapsulation of methods

For some methods that are only used inside the class, they are not provided for external use. In this way, we can use private for privatization.
Private function formatName () {}// this method can only be called within the class using $ this
Function showName (){
$ This-> formatName ();
}

② Encapsulation of attributes + set/get Method

To control the setting and reading of attributes, You Can privatize the attributes and require users to set them using the set/get method we provide.
Private $ age;
Function setAge ($ age ){
$ This-> age = $ age;
}
Function getAge (){
Return $ this-> age;
}
$ Object-> getAge ();
$ Object-> setAge (12 );

③ Encapsulation of attributes + magic methods

Private $ age;
Function _ get ($ key ){
Return $ this-> $ key;
}
Function _ set ($ key, $ value ){
$ This-> $ key = $ value;
}
$ Object-> age; // when accessing the private property of an object, the _ get () magic method is automatically called and the accessed property name is passed to the _ get () method;
$ Object-> age = 12; // when setting the private property of an object, the _ set () magic method is automatically called, and the set property name and attribute value are passed to _ set () method;

Note ]:In the magic method, you can use the branch structure to determine the difference between the $ key and perform different operations.

4. encapsulation magic methods:

① _ Set ($ key, $ value): this parameter is automatically called when a class private attribute is assigned. Two parameters are passed to the method during the call: the attribute name and attribute value to be set;

② _ Get ($ key): it is automatically called when reading private properties of the class. A parameter is passed to the method during the call: name of the attribute to be read;

③ _ Isset ($ key): it is automatically called when the isset () function is used externally to detect private attributes.

>>> Isset () is used outside the class. Private attributes are detected and cannot be detected by default. False

>>> Therefore, we can use the _ isset () function to return internal detection results during automatic calling.

function __isset($key){       return isset($this->$key);       }

When isset ($ Object Name-> private attribute) is used externally, the result returned by _ isset () is automatically called!

④ _ Unset ($ key): it is automatically called when the unset () function is used externally to delete private attributes;

    function __unset($key){      unset($this->$key);      }

When the external uses unset ($ Object Name-> private attribute); When deleting an attribute, the attribute name is automatically passed to _ unset () and handled by this magic method.

One instance

Class Person {public $ name; public $ age; public $ sex; function _ construct ($ name, $ age, $ sex) {$ this-> name = $ name; $ this-> setAge ($ age); $ this-> setSex ($ sex);} function setAge ($ age) {if ($ age >=0 & $ age <= 120) {return $ this-> age = $ age;} else {die ("Incorrect age Input !!! ") ;}} Function setSex ($ sex) {if ($ sex =" female "| $ sex =" male ") {return $ this-> sex = $ sex;} else {die ("Incorrect Gender input !!! ") ;}} Function say () {echo" My name is {$ this-> name}, my age is {$ this-> age }, my gender is {$ this-> sex} <br> ";}} class Work extends Person {private $ position; function _ construct ($ name, $ age, $ sex, $ position) {parent ::__ construct ($ name, $ age, $ sex); $ this-> job = $ job; $ this-> setPosition ($ position);} function setPosition ($ position) {$ arr = ['directory', 'President', 'programmer ', 'cleaner']; if (in_array ($ position, $ arr) {return $ this-> position = $ position;} else {die ("this position does not exist ");}} function _ set ($ key, $ value) {if ($ key = "age") {return parent: setAge ($ value );} elseif ($ key = "sex") {return parent: setSex ($ value);} elseif ($ key = "position ") {return $ this-> setPosition ($ value);} return $ this-> $ key = $ value;} function say () {parent: say (); echo "my position is {$ this-> position}" ;}}$ zhangsan = new Work ("James", 22, "male", "Director "); $ zhangsan-> setSex ("female"); $ zhangsan-> setAge (30); // $ zhangsan-> setPosition ("Chairman "); $ zhangsan-> position = "Chairman"; $ zhangsan-> name = "lisi"; $ zhangsan-> say ();

Iii. Polymorphism

3.1. What is polymorphism?

The premise of polymorphism implementation is inheritance.

1. A class is inherited by multiple sub-classes. If a method of this class shows different functions in multiple sub-classes, we call this behavior a polymorphism. Method rewriting in PHP,

2. Necessary ways to achieve polymorphism:

(1) subclass inherits the parent class;

(2) override the parent class method;

(3) parent class references Child class objects;

Class Computer {function fangfa (InkBox $ a, Paper $ B) {// echo referenced by the parent class "will be printed soon... <br> "; $ a-> color (); $ B-> sizes (); echo "Print finished... <br>" ;}} class Color implements InkBox {function color () {echo "loading color ink cartridges <br>"; echo "for color ink cartridges <br>" ;}} class White implements InkBox {function color () {echo "loading black and white ink cartridges <br>"; echo "Realizing black and white ink cartridges <br>" ;}} class A4 implements Paper {function sizes () {echo "loading A4 Paper <br>"; echo "Implementing A4 Paper <br>" ;}} class A5 implements Paper {function sizes () {echo "implement A5 paper <br>" ;}}$ com = new Computer (); // create an object $ com-> fangfa (new Color (), new A4 (); // subclass object

The above section comprehensively analyzes the three main features of PHP's object-oriented architecture, that is, all the content shared by the editor. I hope to give you a reference and support for the customer's home.

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.