search
Homephp教程php手册PHP多态代码实例

PHP多态代码实例

Jun 13, 2016 am 08:59 AM
phpmaincodePolymorphismExamplearticleDemouse

PHP多态代码实例

          这篇文章主要介绍了PHP多态代码实例,本文用2个代码实例来演示PHP中的多态,需要的朋友可以参考下

 

 

          多态定义:只关心一个接口或者基类,而不关心一个对象的具体类。(同一类型,不同结果)

          这里两个例子:

          第一个,我们发现,基类定义了标准,子类进行了自我规则的实现。这是多态的一个要求。同时,这是满足重写;实际上这是不同类的不同表现;没有严格满足一个接口,或者基类编程。因为你调用的时候不是 stu->showGrade() 而是各自自己的方法;

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

class stu{

 

public function showGrade(){

echo "base class";

}

 

}

 

 

class xiaomin extends stu{

 

public function showGrade(){

echo "is son show 80";

}

}

 

class xiaoli extends stu{

 

public function showGrade(){

echo "is son show 60";

}

}

 

function doit($obj){

 

if(get_class($obj) != "stu"){

$obj->showGrade();

}

 

}

 

doit(new xiaoli());

doit(new xiaomin());

        第二个例子:dovoice 参数规定了$obj 为animal,意识就是用接口 接受了 实现类对象。了向上转型。这就符合同一类型,不同结果了,这就是多态;

        实际上在Java中 会是 animal a = new dog();这样子的;因为PHP 是若类型语言。没有对象转型机制。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

interface animal{

public function voice();

}

 

class cat implements animal{

public function voice(){

echo "miao~~~
";

}

}

 

class dog implements animal{

public function voice(){

echo "wang ~~~
";

}

}

 

function dovoice(animal $obj){

$obj->voice();

}

 

 

dovoice(new dog());

dovoice(new cat());

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools