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){    //instanceof 关键字:对象是否属于接口
            $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:我们开始种植胡萝卜~
    */

猜你喜欢

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