PHP实现多态的2种方法(附带实例)
多态性是指同一操作作用于不同类的实例,将产生不同的执行结果,即不同类的对象收到相同的消息时,得到不同的结果。
在 PHP 中,实现多态的方法有两种,包括通过继承实现多态和通过接口实现多态。
在 PHP 中,实现多态的方法有两种,包括通过继承实现多态和通过接口实现多态。
PHP通过继承实现多态
通过继承可以实现多态的效果,下面通过一个实例来理解实现多态的方法:<?php abstract class Vegetables{ //定义抽象类 Vegetables abstract function go_Vegetables(); //定义抽象方法 go_Vegetables } class Vegetables_potato extends Vegetables{ //马铃薯类继承蔬菜类 public function go_Vegetables(){ //重写抽象方法 echo "我们开始种植马铃薯"; //输出信息 } } class Vegetables_radish extends Vegetables{ //萝卜类继承蔬菜类 public function go_Vegetables(){ //重写抽象方法 echo "我们开始种植萝卜"; //输出信息 } } function change($obj){ //自定义方法根据对象调用不同的方法 if($obj instanceof Vegetables ){ $obj->go_Vegetables(); }else{ echo "传入的参数不是一个对象"; //输出信息 } } echo "实例化 Vegetables_potato: "; change(new Vegetables_potato()); //实例化 Vegetables_potato echo "<br/>"; echo "实例化 Vegetables_radish: "; change(new Vegetables_radish()); //实例化 Vegetables_radish ?>运行结果如下图所示:
实例化 Vegetables_potato: 我们开始种植马铃薯
实例化 Vegetables_radish: 我们开始种植萝卜
PHP通过接口实现多态
下面通过接口的方式实现和上面实例一样的效果:<?php interface Vegetables{ //定义接口 Vegetables public function go_Vegetables(); //定义接口方法 } class Vegetables_potato implements Vegetables{ //Vegetables_potato 实现 Vegetables 接口 //Vegetables_potato 实现 Vegetables 接口 public function go_Vegetables(){ //定义 go_Vegetables 方法 echo "我们开始种植马铃薯"; //输出信息 } } class Vegetables_radish implements Vegetables{ //Vegetables_radish 实现 Vegetables 接口 //Vegetables_radish 实现 Vegetables 接口 public function go_Vegetables(){ //定义 go_Vegetables 方法 echo "我们开始种植萝卜"; //输出信息 } } function change($obj){ //自定义方法根据对象调用不同的方法 if($obj instanceof Vegetables ){ $obj->go_Vegetables(); }else{ echo "传入的参数不是一个对象"; //输出信息 } } echo "实例化 Vegetables_potato: "; change(new Vegetables_potato()); //实例化 Vegetables_potato echo "<br/>"; echo "实例化 Vegetables_radish: "; change(new Vegetables_radish()); //实例化 Vegetables_radish ?>运行结果为:
实例化 Vegetables_potato: 我们开始种植马铃薯
实例化 Vegetables_radish: 我们开始种植萝卜