Understanding and using polymorphism in PHP []_php Abstracts

Source: Internet
Author: User
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, while sharing 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.
You can simulate polymorphism as a button in the real world. Everyone knows how to use a button: you just have to exert pressure on it. A button "really is", however, depends on what it is connected to and using 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. You can create interchangeable objects that are selected according to your needs, compared to the different courses described in the messy conditional statement. This is the basic goal of polymorphism.
Interfaces Interface
An interface is similar to a class (class) except that it cannot contain code. Interfaces can define method names and parameters, but not the contents of methods. Any class that implements an interface must implement all the methods defined in the interface. A class can implement multiple interfaces.
Use the "interface" keyword to declare an interface:
Copy Code code as follows:

Interface MyInterface {
Methods
}

is attached to a class, using the "Implements" keyword (multiple interfaces, which can be separated by commas):
Copy Code code as follows:

Class MyClass implements MyInterface {
Methods
}

You can define a method in an interface as you would in a class, except that there is no method body (part of curly braces).
Copy Code code as follows:

Interface MyInterface {
Public function dothis ();
Public function dothat ();
Public Function SetName ($name);
}

All the methods defined here must be contained in any class that implements it, as described in the interface. (Read the code note below)
Copy Code code 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 an abstract class must implement all the abstract methods defined in the abstract class.
Abstract classes are defined in the same way as classes, but are preceded by an abstract keyword.
Copy Code code as follows:

Abstract class Myabstract {
Methods
}

and is appended to the class with the ' extends ' keyword:
Copy Code code as follows:

Class MyClass extends Myabstract {
Class methods
}

As in ordinary classes, common methods 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 Code code as follows:

Abstract class Myabstract {
Public $name;
Public Function Dothis () {
Do this
}
Abstract public Function dothat ();
Abstract public Function SetName ($name);
}

Let's say you have an article article class responsible for managing the articles on your site. It contains information about the article, including: title, author, date, and category.
Just like the following:
Copy Code code 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", which is a common way to separate the class name from the 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 want to do this as follows:
Copy Code code 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;
}
}

The solution is ugly, but it's 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 one thing a class should do, and it should be done 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 proposed: managing articles and formatting their data. In this tutorial, we'll refactor our formatted code into a new class, and then we'll see how easy it is to use polymorphism.
Step 2: Define your interface Define Your Interface
The first thing we should do is define the interface, and it's important to try to figure out how to define your interface, because any changes to it will need to change the code that calls it.
In our case, we'll use a simple interface to define a method:
Copy Code code as follows:

Interface Poly_writer_writer {
Public Function write (poly_base_article $obj);
}

It is as simple as that, we have defined a common method write (), which accepts an article object as an argument. Any class that implements the writer interface will ensure that this method is available.
Tip: If you want to strictly limit the types of parameters passed to your methods and functions, you can use type hints, just as we have done in the write () method, which can only accept the number of Poly_base_article object types
According Unfortunately, in the current version of PHP, the return type hint is not supported, so you have to be careful about the type of return value.
Step 3: Create implementation class Create Your implementation
After defining the interface, it's time to create a class to really work on it. In our example, we need to output two formats. In this way, we need two writer classes: XMLWriter and Jsonwriter. From passing over the
The Article object extracts the data and then formats the information completely depending on these classes.
The following is an example of the XMLWriter class:
Copy Code code 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 functionality that is formatted as XML.
Now let's look at the Jsonwriter class:
Copy Code code 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 carte blanche to handle a particular format, not the other. There is no other part of your application that needs to be concerned about how it works to use it,
Thanks for our interface.
Step 4: Using your interface use Your implementation
After our new class definition, it's time to revisit our article class, and all the code in the original write () method has been separated into our new class.
All we have to do now is use these new classes, like this:
Copy Code code as follows:

Class Poly_base_article {
//...
Public Function write (Poly_writer_writer $writer) {
Return $writer->write ($this);
}
}

Gets a Writer object obtaining a Writer
You may wonder where you should get a writer object to begin with, 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 a factory class to obtain request data and then create an object:
Copy Code code 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 (' unsupported format ');
}
}

As I said, there are a lot of other strategies available, depending on your needs. In this example, a request variable is used to select which format to use. It constructs a class name based on the request variable to detect whether it exists,
Then a new writer object is 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 Code code 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. Then we tried to get a factory object from the factory factory, and roll back to the default (XMLWriter) if the exception occurred.
Finally, we pass the Write () method of the writer object to our article, outputting 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 case of using polymorphism.
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, do not hesitate to ask questions in the comments!
From: http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Original published in: http://ihacklog.com/?p=4703

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.