This article mainly introduced the PHP object-oriented polymorphism implementation method, simply explained the object-oriented polymorphism principle and unifies the concrete example to give the PHP to realize the polymorphism the related operation skill, needs the friend can refer to the next
In this paper, we describe the object-oriented multi-state implementation method of PHP. Share to everyone for your reference, as follows:
Polymorphic : A parent class reference to a subclass object that can redefine or alter the nature and behavior of a class based on the use of the class's context (methods that invoke different classes using the input classes). Interface refers to the class object that implements the interface.
Object-oriented: the data (attribute), the method of manipulating the data, the logic, forming a class, abstracting the class to form the object, using the class through the object;
<?phpclass work{ function polymorphic ($obj) { //Check if reference type (obj Inherits animal Class) if ($obj instanceof animal) { $obj Fun (); } else{ echo "no function"; } } If you need to specify a class (Specify Cat class, including cat subclass) function Bose (cat $obj) { $obj->fun ();} } Abstract class Abstraction animal{abstract function Fun ();} Cat Cat class Cat extends animal{ function fun () { echo "cat say Miaomiao ..."; }} Dog Dogs class Dog extends animal{ function fun () { echo "dog say Wangwang ..."; }} Class Mouse extends cat{}//first new work class $new_work = new Work ();//Then New_work method is called through Polymorphic object, passing in different classes implement parent class reference to child class object Interface refers to a class object (polymorphic) that implements an interface. $new _work->polymorphic (new cat); Echo ' <br/> '; $new _work->polymorphic (new dog); Echo ' <br/> ';// Specifies the class mode imitation Java$new_work->bose (New Cat ()), Echo ' <br/> ';//If other classes are transmitted, or if the cat class is not inherited, the error//$new _work->bose (New Dog ()) echo ' <br/> ';//This will not error $new_work->bose (new mouse ());
Operation Result:
Cat say Miaomiao...dog say Wangwang...cat say Miaomiao...cat say Miaomiao ...