PHP 面向对象通过接口实现多态

<?php
    interface Vegetables{   //定义接口Vegetables
        public function go_Vegetables();    //定义接口方法
    }
    class Vegetables_radish implements Vegetables{  //Vegetables_radish 实现 Vegetables 接口
        public function go_Vegetables(){    //定义go_Vegetables方法
            echo "我们开始种植胡萝卜~";
        }
    }
    class Vegetables_potato implements Vegetables{
        public function go_Vegetables(){    //定义go_Vegetables方法
            echo "我们开始种植马铃薯~";
        }
    }
    function change($obj){  //自定义方法根据对象调用不同的方法
        if ($obj instanceof Vegetables){    //instanceof 关键字:对象是否属于接口
            $obj->go_Vegetables();
        }else{
            echo "传入的参数不是一个对象";
        }
    }
    echo "实例化Vegetables_radish:";
    change(new Vegetables_radish());
    echo "<br/>";
    echo "实例化Vegetables_potato:";
    change(new Vegetables_potato());    //实例化
    /* 运行结果:
        实例化Vegetables_radish:我们开始种植胡萝卜~
        实例化Vegetables_potato:我们开始种植马铃薯~
    */

猜你喜欢

转载自blog.csdn.net/Qjy_985211/article/details/81623828