PHP design pattern five: polymorphism

WBOY
Release: 2016-07-29 08:51:09
Original
1019 people have browsed it

data-id="1190000005068760" data-license="cc">

Original address: PHP Design Patterns (5): Polymorphism

Introduction

In PHP Design Patterns (4): Inheritance we introduced inheritance, A method of programming using extends.
In PHP Design Patterns (2): Abstract Classes and Interfaces, we introduced interfaces. In fact, there are also programming methods that use interfaces, which is polymorphism.
Like C/C++, Java, Python and other languages, PHP also supports polymorphism. Polymorphism is more of an object-oriented programming concept, allowing objects of the same type to execute the same interface but implement different logical functions.

Polymorphism/Polymorphism

Let’s use animals, whales and carps as examples:

<code><?php
interface IEat {
  function eatFish();
  function eatMoss();
}

class Whale implements IEat {
  public function eatFish() {
    echo "Whale eats fish.\n";
  }
  public function eatMoss() {
    echo "Whale doesn't eat fish\n";
  }
}

class Carp implements IEat {
  public function eatFish() {
    echo "Carp doesn't eat moss.\n";
  }
  public function eatMoss() {
    echo "Carp eats moss.\n";
  }
}

$whale = new Whale();
$whale->eatFish();
$whale->eatMoss();
$carp = new Carp();
$carp->eatFish();
$carp->eatMoss();
?></code>
Copy after login

Run it:

<code>$ php Inheritance.php
Whale eats fish.
Whale doesn't eat fish.
Carp eats moss.
Carp doesn't eat moss.</code>
Copy after login

Note that PHP function definitions do not include return values, so it is completely possible to return different types of data to different interface implementations . This is different from languages ​​such as C/C++ and Java. In addition, returning different types of data, or even returning no results, will increase maintenance costs for programming, which is different from the original intention of using interfaces (interfaces are designed to encapsulate implementation, and different return values ​​actually require the caller to to understand the implementation).

Summary

Use polymorphism reasonably to implement different interfaces, simplify your programming model, and make the code easy to maintain.

The above has introduced PHP design pattern five: polymorphism, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

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