//猪八戒类 class Pig{ public function display(){ echo '猪八戒下凡,哼哼坠地! <br/>'; } } //main //打开蓝灯 $light = new Light(); $blueglass = new BlueGlass(); $light->TrunOn($blueglass); //打开绿灯 $greenglass = new GreenGlass(); $light->TrunOn($greenglass); //坏了猪八戒从手电筒里面出生了, 现在做了类型限制 $pig = new Pig(); $light->TrunOn($pig); //Catchable fatal error: Argument 1 passed to Light::TrunOn() must be an instance of BlueGlass /**** 如果按PHP本身特点,不检测类型, 本身就可以说是多态的,甚至变态的.
//猪八戒类 class Pig{ public function display(){ echo '猪八戒下凡,哼哼坠地! <br/>'; } } //main //打开红灯 $light = new Light(); $redglass = new RedGlass(); $light->TrunOn($redglass); //打开绿灯 $greenglass = new GreenGlass(); $light->TrunOn($greenglass); //坏了猪八戒从手电筒里面出生了 $pig = new Pig(); $light->TrunOn($pig); /***** 分析 与java那段出错程序相比 php没报错, 因为PHP是弱类型动态语言.