Chapter 2 object-oriented features

Source: Internet
Author: User

Learning points:
1. OOP Encapsulation
2. Inheritance of OOP
3. OOP Polymorphism

 

The three main features of object-oriented are encapsulation, inheritance, and polymorphism.

1. OOP Encapsulation

Hide the fields and implementation details of an object. Only open interfaces are provided to control the access level for reading and modifying fields in the program.
Combine abstract data with behaviors (or functions) to form an organic whole, that is, to integrate data
The source code of the operation data is organically combined to form a "class", where data and functions are members of the class.

 

Field Scope
1. public (accessible outside the class)
2. private (accessible within the class)
3. protected is protected (class and subclass can be accessed, and class cannot be accessed)

 

Create a private field so that external access is unavailable.

Class Computer {// class field (member) private $ _ name = 'lenovo 100'; private $ _ model = 'lx ';}

 

Use a public method as the entry to access private fields, but use the $ this keyword.

Class Computer {// class field (member) private $ _ name = 'lenovo 100'; private $ _ model = 'lx '; // access the private field function run () {echo $ this-> _ name ;}}$ computer-> run () through public methods ();

 

Attribute operation (assign values and values of private fields)

Two public methods can be designed. One method is setName (), which is used to assign values. The other method is getName (),
Used for value.

Class Computer {// class field (member) private $ _ name; private $ _ model; // value function setName ($ _ name) {$ this-> _ name = $ _ name;} // value: function getName () {return $ this-> _ name ;}$ computer = new Computer (); $ computer-> setName ('ibm '); echo $ computer-> getName ();

If there are ten fields, it takes 20 methods to assign values and values. Is there a simpler method?
What about it? PHP has two built-in methods (interceptor) specifically used for values and values: __set () ,__ get ().

Class Computer {// class field (member) private $ _ name; private $ _ model; // All field assignments are carried out here function _ set ($ _ key, $ _ value) {$ this-> $ _ key = $ _ value;} // the value of all fields is here function _ get ($ _ key) {return $ this-> $ _ key ;}$ computer = new Computer (); $ computer-> _ model = 'lx '; echo $ computer-> _ model;

Method PRIVATE: Some methods in the class do not need to be made public, but are only part of the operation.
Methods can also be encapsulated.

Class Computer {// class field (member) private $ _ name; private $ _ model; // private method private function getEcho () {echo 'my method of privatization ';} // The public method is usually the external Entry public function run () {$ this-> getEcho ();}} $ computer = new Computer (); $ computer-> run ();

Suggestion: If there is no modifier before the method, it is a public method that is externally accessible, but to make the program more
It is recommended to add public in front.

 

Constant (constant)
A constant can be defined in a class to indicate a value that does not change. For any object instantiated from this class
The value remains unchanged throughout the lifecycle of these objects.

class Computer {    const PI = 3.1415926;}echo Computer::PI;

 

Static class member
Sometimes, you may need to create fields and Methods shared by all the class instances.
But cannot be called by any specific object.

class Computer {    public static $_count = 0;}echo Computer::$_count;

In general, fields must be made private. So you may need to do this:

class Computer {    private static $_count = 0;    public static function setRun() {        self::$_count ++;    }    public static function getRun() {        return self::$_count;    }}Computer::setRun ();echo Computer::getRun ();

 

Instanceof keyword
PHP5 has an instanceof keyword, which can be used to determine whether an object is an instance of a class or
Subclass, or implements a specific interface and performs corresponding operations.

class Computer {    }$computer = new Computer ();echo ($computer instanceof Computer);

 

Ii. OOP inheritance

Inheritance is a mechanism for obtaining one or more classes from a base class.
A class that inherits from another class is called a subclass of this class. This relationship is typically compared with the parent class and the Child class. Subclass will follow
Features of the parent class. These features consist of attributes and methods. Sub-classes can add new features outside the parent class, so sub-classes also
It is called the "extension" of the parent class ".

In PHP, class inheritance is implemented using the extends keyword. The class that inherits from other classes is a subclass or a derived class.
The class inherited by the class becomes the parent class or base class. (PHP only supports single inheritance, and PHP does not support method overloading ).

Class Computer {private $ _ name = 'lenovo 100'; private function _ get ($ _ key) {return $ this-> $ _ key;} public function run () {echo 'I am a parent class';} class NoteBookComputer extends Computer {}$ notebookcomputer = new NoteBookComputer (); $ notebookcomputer-> run (); echo $ notebookcomputer-> _ name;

 

Override of fields and Methods)
In some cases, the fields and methods of the parent class are not particularly required. You can modify the fields and methods of the parent class by rewriting the child classes.
Fields and methods.

Class Computer {public $ _ name = 'lenovo 120 '; protected function run () {echo' I am a parent class ';}} class NoteBookComputer extends Computer {public $ _ name = 'ibm '; public function run () {echo' I am a subclass ';}}

 

Subclass calls the fields or methods of the parent class
To ensure security, we generally encapsulate the methods of the parent class so that the external class cannot be called and can only be inherited.
. At this time, the parent class needs to be called through the subclass operation.

Class Computer {protected $ _ name = 'lenovo 100'; protected function run () {echo 'I am the parent class';} class NoteBookComputer extends Computer {public function getName () {echo $ this-> _ name;} public function getRun () {echo $ this-> run ();}}

 

Call the method of the parent class by rewriting
Sometimes, we need to use the override method to call the Method Content of the parent class.
Syntax: parent class name: method () or parent: method () can be called.

Class Computer {protected function run () {echo 'I am the parent class';} class NoteBookComputer extends Computer {public function run () {echo Computer: run ();}}

 

The final keyword can prevent the class from being inherited. Sometimes, you only want to be an independent class and do not want to be inherited and used by other classes,
You must use this keyword. We recommend that you add this keyword to a separate class.

Final class Computer {// class that cannot be inherited final public function run () {}// method that cannot be inherited} class NoteBookComputer extends Computer {// an error will be reported}

 

Abstract classes and methods (abstract)
Abstract methods are special. They are declared only in the parent class, but are implemented in the subclass. Only the class declared as abstract can be declared
The abstract method.

Rules:
1. abstract classes cannot be instantiated and can only be inherited.
2. the abstract method must be overwritten by the quilt method.

Abstract class Computer {abstract function run ();} final class NotebookComputer extends Computer {public function run () {echo 'I implemented ';}}

 

Interface)
The interface defines the general specification for implementing a certain service, declares the required functions and constants, but does not specify how to implement them.
The reason for not giving implementation details is that different entities may need different methods to implement public methods.
. The key is to establish a set of general principles that must be implemented. Only when these principles are met can this interface be implemented.

Rules:
1. All classes are abstract methods (abstract is not required)
2. The interface abstract method must be public.
3. The member (field) must be a constant.

Interface Computer {const NAME = 'lenovo 120 '; public function run ();} final class NotebookComputer implements Computer {public function run () {echo 'method for implementing the interface '; }}$ notebookcomputer = new NoteBookComputer (); $ notebookcomputer-> run (); echo Computer: NAME;

 

Subclass can implement multiple interfaces

Interface Computer {const NAME = 'lenovo 120 '; public function run ();} interface Notebook {public function book ();} final class NotebookComputer implements Computer, notebook {public function run () {echo 'method implementing the interface';} public function book () {echo 'method implementing the interface ';}}

 

Iii. Polymorphism

Polymorphism means that OOP can redefine or change the nature or behavior of a Class Based on the context of the class used, or
There are many different implementations of the port, namely, polymorphism. Different subclass objects can be treated as parent classes to shield different subclasses.
Differences between objects, write common code, and make general programming to adapt to the changing needs.

Interface Computer {public function version (); public function work ();} class NotebookComputer implements Computer {public function version () {echo 'lenovo 100';} public function work () {echo 'notebook is running at any time! ';}} Class program topcomputer implements Computer {public function version () {echo 'ibm';} public function work () {echo 'the desktop Computer is running on the workstation! ';}} Class Person {public function run ($ type) {$ type-> version (); $ type-> work ();}} $ person = new Person (); $ your topcomputer = new your topcomputer (); $ notebookcomputer = new NoteBookComputer (); $ person-> run ($ notebookcomputer );

 Note: This article is a video tutorial from Li Yanhui PHP. This article is intended for communication purposes only and cannot be used for commercial purposes. Otherwise, the consequences will be borne by you.

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.