Home > Backend Development > PHP Tutorial > Understanding and applying polymorphism in PHP [Translation]_PHP Tutorial

Understanding and applying polymorphism in PHP [Translation]_PHP Tutorial

WBOY
Release: 2016-07-21 15:25:48
Original
944 people have browsed it

What is polymorphism?
Polymorphism is a long word, but it represents a very simple concept.
Polymorphism describes the object-oriented programming model in which classes have different functions 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 code from different classes.
Polymorphism can be compared to a button in the real world. Everyone knows how to use a button: you just put pressure on it. What a button "really is", however, depends on what it is connected to and the context in which it is used - 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. Rather than messy conditional statements describing actions in different classes, you can create interchangeable objects chosen based on your needs. This is the basic goal of polymorphism.
Interfaces
An interface is similar to a class, except that it cannot contain code. An interface can define method names and parameters, but not the content of the methods. 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:

Copy the code The code is as follows:

interface MyInterface {
// methods
}

is attached to a class using the "implements" keyword (multiple interfaces can be separated by commas):
Copy code The code is as follows:

class MyClass implements MyInterface {
// methods
}

in the interface Methods can be defined in a class just like in a class, except that there is no method body (the part enclosed in curly braces).
Copy code The code is as follows:

interface MyInterface {
public function doThis();
public function doThat ();
public function setName($name);
}

All methods defined here must be included as described in the interface in any class that implements it middle. (Read the code comments below)
Copy code The 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 be public!
}
public function setName() {
// missing the name argument!
}
}

Abstract Class Abstract Class
Abstract class is a mixture of interface and class. It can define methods just like an interface. A class that inherits from an abstract class must implement all abstract methods defined in the abstract class.
Abstract classes are defined in the same way as classes, but with the abstract keyword appended in front.
Copy code The code is as follows:

abstract class MyAbstract {
// methods
}

and is attached to the class using the 'extends' keyword:
Copy the code The code is as follows:

class MyClass extends MyAbstract {
// class methods
}

Just like in a normal class, normal methods as well as any abstract methods (using keyword "abstract") can be added in abstract defined in the class. An abstract method behaves like a method defined in an interface, and extending classes that inherit it must implement exactly the same definition.
Copy code The 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 class responsible for managing articles on your website. It contains information about the article, including: title, author, date, and category.
Like this:
Copy code 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 classes in this tutorial use the "package_component_Class" naming convention, which is A general method for separating class names into virtual namespaces to avoid naming conflicts.
Now you want to add a method to output information in various formats, such as XML and JSON. You might want to do something like this:
Copy the code 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's reliable - at least for now. Ask yourself what will happen in the future, when we need to add more formats? You can keep editing this class and add more and more cases,
but now you are just diluting (FIX ME: diluting) your class.
An important principle of OOP is that a class should do one thing and do it well.
With this in mind, conditional statements should be a red flag that your class is trying to do too many different things. This is where polymorphism comes in.
In our example, two tasks are clearly presented: managing articles and formatting their data. In this tutorial, we'll refactor our formatting code into a new class, and then we'll discover how easy it is to use polymorphism.
Step 2: Define Your Interface
The first thing is that we should define the interface. It is important to try to figure out how to define your interface, because any changes to it will require changes. The code that calls it.
In our example, we will use a simple interface to define a method:
Copy the code The code is as follows:

interface poly_writer_Writer {
public function write(poly_base_Article $obj);
}

It’s that simple, we have defined a public method write() which accepts a Article object as parameter. Any class that implements the Writer interface will be sure to have this method.
Tips: If you want to strictly limit the parameter types passed to your methods and functions, you can use type hints, like we have done in the write() method, which can only accept poly_base_Article object types Data
data. Unfortunately, in the current version of PHP, return type hints are not supported, so you need to be careful about the type of the return value.
Step 3: Create Your Implementation
After defining the interface, it’s time to create the class to do the real work. In our case, we need to output two formats. In this way, we need two Writer classes: XMLWriter and JSONWriter. It's entirely up to these classes to extract data from the passed
Article object and then format the information.
The following is an example of the XMLWriter class:
Copy code 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 contains functions for formatting to XML.
Now let’s look at the JSONWriter class:
Copy the code 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, our code specific to each format is contained in a separate class. Each class has sole responsibility for handling a specific format and not others. No other part of your application needs to care about how these work in order to use it,
thanks to our interfaces.
Step 4: Use Your Implementation
After our new class is defined, it is time to review our Article class. All the code in the original write() method has been separated , entering our new category.
All our methods need to do now is use these new classes, like this:
Copy the codeThe code is as follows:

class poly_base_Article {
//...
public function write(poly_writer_Writer $writer) {
return $writer->write($this);
}
}

Obtaining a Writer
You may be wondering where to get a Writer object to start, because you need to pass a Writer object to this method.
It’s all up to you, and there are many strategies. For example, you might use a factory class to get the request data and then create an object:
Copy the code 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('Unsupported format');
}
}

Like I said, depending on your needs, there are There are many other strategies available. In this example, a request variable is used to select which format is to be used. It constructs a class name based on the request variable, checks whether it exists,
and returns a new Writer object. If no class of that name exists, throw an exception and let the client code decide what to do next.
Step 5: Put It All Together
When everything is in place, here is how our client code is put together:
Copy Code The 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 create a sample Article object to work with. 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 the write() method of our Article and output the result.
Conclusion

In this tutorial, I provide an introduction to polymorphism and explain interfaces in PHP. I hope you realize that I'm only showing you one potential use case for polymorphism.
Polymorphism is an elegant way to avoid ugly conditional statements in your OOP code. It follows the principle of keeping your components separate, and it's an integral 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/
Original text published at: http://ihacklog.com/?p= 4703

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324073.htmlTechArticleWhat is polymorphism? Polymorphism is a long word, but it represents a very simple concept. Polymorphism describes the differences between classes in object-oriented programming...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template