'. $ Obj-> title .'

Source: Internet
Author: User
Tags php source code
Document directory
  • Step 2: Define your interface define your interface
  • Step 3: Create Your implementation
  • Step 4: Use your interface use your implementation
  • Step 5: Put them together put it all together
  • Conclusion conclusion

Brief Introduction: This is a detailed page for understanding and using polymorphism in PHP. It introduces PHP, related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 342560 'rolling = 'no'> in Object-Oriented Programming, polymorphism is a powerful and basic tool. It can be used to create a more organic stream in your application. This tutorial will introduce the general concept of polymorphism and how it can be easily deployed in PHP.

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.

The"Interface"Keyword declares an interface:

interface MyInterface {    // methods}

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

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.

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)

// Valid validclass 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 invalidclass 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.

abstract class MyAbstract {    // methods}

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

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.

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:
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:

class poly_base_Article {    //...    public function write($type) {        $ret = '';        switch($type) {            case 'XML':                $ret = '';                $ret .= '';                $ret .= '' . $obj->author . '';                $ret .= '
 
  ' . $obj->date . '
 ';                $ret .= '';                $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 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 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:

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:

class poly_writer_XMLWriter implements poly_writer_Writer {    public function write(poly_base_Article $obj) {        $ret = '';        $ret .= '';        $ret .= '' . $obj->author . '';        $ret .= '
 
  ' . $obj->date . '
 ';        $ret .= '';        $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:

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:

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:

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 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:

$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 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 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

Disclaimer: This site complies with the signature-non-commercial use-share the 2.5 sharing protocol in the same way. For details, refer to conversion from hacklog. [wilderness light-less weblog]

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/342560.html pageno: 6.

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.