Understanding and Using polymorphism in PHP [Translate] _ PHP Tutorial

Source: Internet
Author: User
Understand and use the [Translation] of polymorphism in PHP. What is polymorphism? Polymorphism (Polymorphism) is a very long word, but it represents a very simple concept. Polymorphism describes the differences in classes in object-oriented programming models. What is polymorphism?
Polymorphism (Polymorphism) is a very long word, but it represents a very simple concept.
Polymorphism describes how classes have different functions in object-oriented programming modes, while sharing a common interface.
The advantage of polymorphism is that you don't need to know which class it uses, because they all work with code of different classes in the same way.
Polymorphism can be analogous to a button in the real world. Everyone knows how to use a button: you only need to put pressure on it. A button "does." However, it depends on what it connects to and uses its context-but the result does not affect how it is used. If your boss tells you to press the next button, you have all the information you need to execute the task.
In the world of programming, polymorphism is used to make applications more modular and scalable. You can create swap objects based on your needs compared to courses with messy condition statement descriptions. This is the basic objective of polymorphism.
Interfaces interface
An interface is similar to a class, except that it cannot contain code. The interface can define the method name and parameters, but it is not the content of the method. Any class that implements an interface must implement all methods defined in the interface. A class can implement multiple interfaces.
Use the "interface" keyword to declare an interface:

The code is as follows:


Interface MyInterface {
// Methods
}


To be appended to a class, use the "implements" keyword (multiple interfaces can be separated by commas ):

The code is as follows:


Class MyClass implements MyInterface {
// Methods
}


Methods can be defined in an interface just like in a class, except that there is no method body (in braces.

The code is as follows:


Interface MyInterface {
Public function doThis ();
Public function doThat ();
Public function setName ($ name );
}


All methods defined here must be included in any class that implements it as described in the interface. (Read the following code comments)

The code is as follows:


// VALID
Class MyClass implements MyInterface {
Protected $ name;
Public function doThis (){
// Code that does this
}
Public function doThat (){
// Code that does that
}
Public function setName ($ name ){
$ This-> name = $ name;
}
}
// INVALID
Class MyClass implements MyInterface {
// Missing doThis ()!
Private function doThat (){
// This shoshould be public!
}
Public function setName (){
// Missing the name argument!
}
}


Abstract Class
Abstract classes are a mixture of interfaces and classes. It can define methods like interfaces. Classes inherited from abstract classes must implement all abstract methods defined in abstract classes.
Abstract classes are defined in the same way as classes, but an abstract keyword is appended to them.

The code is as follows:


Abstract class MyAbstract {
// Methods
}


And it is appended to the class with the 'extends 'keyword:

The code is as follows:


Class MyClass extends MyAbstract {
// Class methods
}


Just like in a common class, a common method and any abstract method (using the keyword "abstract") can be defined in an abstract class. The behavior of an abstract method is like a method defined in an interface, and the extension class that inherits it must implement the same definition.

The code is as follows:


Abstract class MyAbstract {
Public $ name;
Public function doThis (){
// Do this
}
Abstract public function doThat ();
Abstract public function setName ($ name );
}


Let's assume that you have an Article class responsible for managing the articles on your website. It contains information about the article, including: title, author, date, and category.
As shown below:

The code is as follows:


Class poly_base_Article {
Public $ title;
Public $ author;
Public $ date;
Public $ category;
Public function _ construct ($ title, $ author, $ date, $ category = 0 ){
$ This-> title = $ title;
$ This-> author = $ author;
$ This-> date = $ date;
$ This-> category = $ category;
}
}


Note: The example class in this tutorial uses the naming convention "package_component_Class". This is a general method used to separate class names into virtual namespaces to avoid name conflicts.
Now you want to add a method to output information in different formats, such as XML and JSON. You may plan to do this as follows:

The code is as follows:


Class poly_base_Article {
//...
Public function write ($ type ){
$ Ret = '';
Switch ($ type ){
Case 'xml ':
$ Ret = '';
$ Ret. = '';
$ Ret. = ''. $ obj-> author .'';
$ Ret. = ''. $ obj-> date .'';
$ Ret. = ''. $ obj-> category .'';
$ Ret. = '';
Break;
Case 'json ':
$ Array = array ('article' => $ obj );
$ Ret = json_encode ($ array );
Break;
}
Return $ ret;
}
}


This solution is ugly, but it is reliable-at least for now. Ask yourself what will happen in the future. when we need to add more formats? You can edit this class and add more and more cases,
But now you are just dilution (fix me: diluting) your class.
An important principle of OOP is that a class should do something, but should do it well.
With this in mind, the condition statement should be a red sign, indicating that your class is trying to make too many different things. This is the use of polymorphism.
In our example, two tasks are clearly proposed: Managing articles and formatting their data. In this tutorial, we will refactor our formatting code to a new class, and then we will find how easy it is to use polymorphism.
Step 2: Define Your Interface
The first thing is that we should define an interface. it is important to think about how to define your interface, because any changes to it will require changes to call its code.
In this example, we will use a simple interface to define a method:

The code is as follows:


Interface poly_writer_Writer {
Public function write (poly_base_Article $ obj );
}


It is that simple. we have defined a public method write (), which accepts an article object as a parameter. Any class that implements the Writer interface will ensure this method.
Tips: If you want to strictly limit the parameter types of methods and functions passed to you, you can use the type prompt, just as we have done in the write () method, it can only accept the number of poly_base_Article object types
Data. Unfortunately, in the current PHP version, the returned type prompt is not supported. therefore, be careful when returning the type.
Step 3: Create Your Implementation
After defining the interface, it is time to create a class to really work. In our example, we need to output two formats. In this way, we need two Writer classes: XMLWriter and JSONWriter. Passed from
The Article object extracts data and then formats the information completely depending on these classes.
The following is an example of the XMLWriter class:

The code is as follows:


Class poly_writer_XMLWriter implements poly_writer_Writer {
Public function write (poly_base_Article $ obj ){
$ Ret = '';
$ Ret. = '';
$ Ret. = ''. $ obj-> author .'';
$ Ret. = ''. $ obj-> date .'';
$ Ret. = ''. $ obj-> category .'';
$ Ret. = '';
Return $ ret;
}
}


As you can see from the class definition, we use the implements keyword to implement our interface. The write () method can be formatted as XML.
Now let's take a look at the JSONWriter class:

The code is as follows:


Class poly_writer_JSONWriter implements poly_writer_Writer {
Public function write (poly_base_Article $ obj ){
$ Array = array ('article' => $ obj );
Return json_encode ($ array );
}
}


Now, each specific format in our code is included in a separate class. Each class is solely responsible for processing specific formats, rather than others. No other part of your application needs to care about how this works before it can be used,
Thank you for your interface.
Step 4: Use Your interface Use Your Implementation
After our new class definition, it is time to review our Article class. all the code in the original write () method has been separated and entered into our new class.
All of our methods now need to use these new classes, like this:

The code is as follows:


Class poly_base_Article {
//...
Public function write (poly_writer_Writer $ writer ){
Return $ writer-> write ($ this );
}
}


Get A Writer object Obtaining A Writer
You may wonder where to get a Writer object, because you need to pass a Writer object to this method.
It depends on you, and there are many strategies. For example, you may use the factory class to obtain request data and create an object:

The code is as follows:


Class poly_base_Factory {
Public static function getWriter (){
// Grab request variable
$ Format = $ _ REQUEST ['format'];
// Construct our class name and check its existence
$ Class = 'Poly _ writer _ '. $ format. 'writer ';
If (class_exists ($ class )){
// Return a new Writer object
Return new $ class ();
}
// Otherwise we fail
Throw new Exception ('unororted format ');
}
}


As I said, there are many other policies available based on your needs. In this example, you can use a Request variable to select the format to use. It constructs a class name based on the request variable and checks whether it exists,
Then a new Writer object is returned. If a class without that name exists, an exception is thrown to let the client code decide what to do next.
Step 5: Put them Together Put It All Together
When everything is in place, how can we put the client code together:

The code is as follows:


$ Article = new poly_base_Article ('polyphism ', 'Steve', time (), 0 );
Try {
$ Writer = poly_base_Factory: getWriter ();
}
Catch (Exception $ e ){
$ Writer = new poly_writer_XMLWriter ();
}
Echo $ article-> write ($ writer );


First, we create an example Article object to work. Then, we try to get a Factory object from the Factory, and roll back to the default (XMLWriter) if an exception occurs ).
Finally, we pass the Writer object to our Article's write () method and output the result.
Conclusion

In this tutorial, I have provided an introduction to polymorphism and explained interfaces in PHP. I hope you will realize that I will only show you one potential case of using polymorphism.
Polymorphism is an elegant way to avoid ugly conditional statements in your OOP code. The principle behind it is to separate your components and it is part of many design patterns. If you have any questions, do not hesitate to ask questions in the comments!
Translation: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Original article published in: http://ihacklog.com /? P = 4703

Why? Polymorphism (Polymorphism) is a very long word, but it represents a very simple concept. Polymorphism describes the differences in classes in object-oriented programming models...

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.