What is polymorphism?
Polymorphism (polymorphism) is a very long word, but it represents a very simple concept.
Polymorphism describes the different functions of classes in object-oriented programming patterns and the sharing of a common interface.
The advantage of polymorphism is that you don't need to know which class it is using, because they all work in the same way with different classes of code.
The polymorphism can be likened to a real-world button. Everyone knows how to use a button: you just have to put pressure on it. A button "is really like this", however, depends on what it and what connection it uses and its context-but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information you need to perform the task.
In the world of programming, polymorphism is used to make applications more modular and extensible. Instead of the messy conditional statements that describe the actions of different courses, you can create interchangeable objects that are selected according to your needs. This is the basic goal of polymorphism.
Interfaces Interface
Interfaces are similar to classes (class), except that they cannot contain code. An interface can define method names and parameters, but not the contents of a method. Any class that implements an interface must implement all of the methods defined in the interface. A class can implement multiple interfaces.
Use the "interface" keyword to declare an interface:
Copy CodeThe code is as follows:
Interface MyInterface {
Methods
}
is attached to a class, using the "Implements" keyword (multiple interfaces, which can be separated by commas):
Copy CodeThe code is as follows:
Class MyClass implements MyInterface {
Methods
}
A method can be defined in an interface as if it were in a class, except that there is no method body (part of the curly brace).
Copy CodeThe code is as follows:
Interface MyInterface {
Public function dothis ();
Public function dothat ();
Public Function SetName ($name);
}
All of the methods defined here must be contained in any class that implements it, as described in the interface. (Read the following code comment)
Copy CodeThe code is as follows:
Legal 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;
}
}
Illegal invalid.
Class MyClass implements MyInterface {
Missing Dothis ()!
Private Function Dothat () {
This should is public!
}
Public Function SetName () {
Missing the name argument!
}
}
Abstract class
An abstract class is a mixture of interfaces and classes. It can define methods like interfaces. Classes that inherit from the abstract class must implement all the abstract methods defined in the abstract class.
Abstract classes are defined in the same way as classes, but with an abstract keyword appended to them.
Copy CodeThe code is as follows:
Abstract class Myabstract {
Methods
}
and is appended to the class with the ' extends ' keyword:
Copy CodeThe code is as follows:
Class MyClass extends Myabstract {
Class methods
}
Just like in a normal 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 exactly the same definition.
Copy CodeThe code is as follows:
Abstract class Myabstract {
Public $name;
Public Function Dothis () {
Do this
}
Abstract public Function dothat ();
Abstract public Function setName ($name);
}
We assume that you have an article article class that manages the articles on your site. It contains information about the article, including: title, author, date, and category.
Just like this:
Copy CodeThe 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 "Package_component_class" naming convention, which is a common method for separating the class name into a virtual namespace to avoid naming conflicts.
Now you want to add a method to output information in a variety of different formats, such as XML and JSON. You might be going to do something like this:
Copy CodeThe 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 continue to edit this class and then add more and more case,
But now you're just diluting (FIX me:diluting) your class.
An important principle of OOP is that a class should do one thing and should do it well.
With this in mind, the conditional statement should be a red flag indicating that your class is trying to do too many different things. This is where polymorphism comes in.
In our example, two tasks are explicitly presented: managing articles and formatting their data. In this tutorial, we'll refactor our formatting code into a new class, and then we'll find out how easy it is to use polymorphism.
Step 2: Define your interface Define Your Interface
The first thing is that we should define the interface and try to figure out how to define your interface is an important thing, because any changes to it will need to change the code that calls it.
In our example, we will use a simple interface to define a method:
Copy CodeThe code is as follows:
Interface Poly_writer_writer {
Public Function write (poly_base_article $obj);
}
It's that simple, we've defined a common method, write (), which takes an article object as a parameter. Any class that implements the writer interface will ensure that this method is available.
Tip: If you want to strictly limit the type of arguments passed to your method and function, you can use the type hint, just as we did in the write () method, which only accepts the number of Poly_base_article object types
According to Unfortunately, in the current version of PHP, the return type hint is not supported, so you should be careful to return the type of the value.
Step 3: Creating an implementation class create Your implementation
Once the interface is defined, it's time to create classes to really work. In our example, we need to output two formats. In this way, we need two writer classes: XMLWriter and Jsonwriter. From the passing over
The article object extracts the data and then formats the information entirely dependent on these classes.
Here is an example of the XMLWriter class:
Copy CodeThe 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 contains features that are formatted as XML.
Now let's look at the Jsonwriter class:
Copy CodeThe 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 of the specific formats in our code is contained in a separate class. Each class has full responsibility for handling specific formats, not others. There is no other part of your application that needs to be concerned about how these work to use it,
Thanks to our interface.
Step 4: Use your interface using the Your implementation
After our new class definition, it's time to revisit our article class, where the code in all the original write () methods has been separated and entered into our new class.
All we have to do now is use these new classes, like this:
Copy CodeThe 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 you should get a writer object starting, because you need to pass a writer object to this method.
It all depends on you, and there are a lot of strategies. For example, you might use the factory class to get the request data and then create an object:
Copy CodeThe code is as follows:
Class Poly_base_factory {
public static function Getwriter () {
Grab request Variable
$format = $_request[' format '];
Construct our class name and check it existence
$class = ' Poly_writer_ '. $format. ' Writer ';
if (class_exists ($class)) {
Return a new Writer object
return new $class ();
}
Otherwise we fail
throw new Exception (' unsupported format ');
}
}
As I said, there are a lot of other strategies available depending on your needs. In this example, choose which format to use with a request variable. It constructs a class name based on the request variable to detect whether it exists,
A new writer object is then returned. If a class without that name exists, throw an exception and let the client code decide what to do next.
Step 5: Put them together put it all Together
When all the stuff is in place, here's how our client code is put together:
Copy CodeThe code is as follows:
$article = new Poly_base_article (' polymorphism ', ' Steve ', Time (), 0);
try {
$writer = Poly_base_factory::getwriter ();
}
catch (Exception $e) {
$writer = new Poly_writer_xmlwriter ();
}
echo $article->write ($writer);
First, we created an example article object to work with. We then try to get a factory object from the factory factory, and roll back to the default (XMLWriter) If the exception occurs.
Finally, we pass the writer object to our article's write () method and output the result.
Conclusion Conclusion
In this tutorial, I provide an introduction to polymorphism and explain the interfaces in PHP. I want you to realize that I'm only showing you a potential use of polymorphism cases.
Polymorphism is an elegant way to avoid ugly conditional statements in your OOP code. It follows the principle of separating your components, and it is part of many design patterns. If you have any questions, don't hesitate to ask in the comments!
Translated from: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Originally published in: http://ihacklog.com/?p=4703
http://www.bkjia.com/PHPjc/324073.html www.bkjia.com true http://www.bkjia.com/PHPjc/324073.html techarticle What is polymorphism? Polymorphism (polymorphism) is a very long word, but it represents a very simple concept. Polymorphism describes the different classes in the object-oriented programming model ...