多态性在 OO 中指 “语言具有以不同方式处理不同类型对象的能力”,但 PHP 是弱类型语言,在这一点上就比较弱,仅有 instance of 可以用于判断对象的类型


多态性的优点:让代码更接近生活中的真实情况


一下是一个非常简单的多态性例子,描述在电脑上安装不同操作系统,linux, OS X, windows 和 computer 是两种不同类型的对象。


interface os{function name();function creator();
}class linux implements os{function name(){echo "Linux";}function creator(){echo " (created by Linus Torvalds)";}
}class windows implements os{function name(){echo "Windows";}function creator(){echo " (created by Microsoft)";}
}class osx implements os{function name(){echo "OSX";}function creator(){echo " (created by Apple)";}
}class computer{function installOS($os){if ($os instanceof os){echo "Installing ";echo $os->name();echo $os->creator()."<br>";}else{echo "not a system";}}
}$myComputer = new computer;$myLinux = new linux;
$myWindows = new windows;
$myOSX = new osx;$myComputer->installOS($myLinux);
$myComputer->installOS($myWindows);
$myComputer->installOS($myOSX);