PHP Multi-State code example
This article mainly introduces the PHP polymorphic code example, this article uses 2 code examples to demonstrate the polymorphism in PHP, the needs of friends can refer to the following
Polymorphic definition: Only one interface or base class is concerned, not the specific class of an object. (same type, different result)
Here are two examples:
First, we find that the base class defines the standard, and the subclass implements the self-rule. This is a requirement for polymorphism. At the same time, this is a satisfying rewrite; in fact, it is different from the different classes, not strictly satisfies an interface, or the base class programming. Because you call not Stu->showgrade () but their own methods;
?
1 2 3 4 5 6 7 8 9 11 + + /+ //+ / + + + + + - - - - + - |
Class stu{ Public Function Showgrade () { echo "base class"; } } Class Xiaomin extends stu{ Public Function Showgrade () { Echo "is son show"; } } Class Xiaoli extends stu{ Public Function Showgrade () { Echo ' is son s "How"; } } Function doit ($obj) { If (Get_class ($obj)! = "Stu") { $obj->showgrad E (); } } doit (new Xiaoli ()); Doit (new xiaomin ()); |
The second example: the Dovoice parameter specifies that $obj is a animal, and consciousness is to accept the implementation class object with the interface. The upward transformation. This conforms to the same type, with different results, which is polymorphic;
In fact, in Java it would be animal a = new dog (); Because PHP is a type language. There is no object transformation mechanism.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 23 |
Interface animal{ Public function voice (); } Class Cat Implements Animal{ Public Function voice () { echo "miao~~~ "; } } Class Dog Implements animal{ Public Function voice () { echo "Wang ~ ~ ~ "; } } function Dovoice (animal $obj) { $obj->voice (); } Dovoice (New Dog ()); Dovoice (New Cat ()); |
http://www.bkjia.com/PHPjc/1022061.html www.bkjia.com true http://www.bkjia.com/PHPjc/1022061.html techarticle PHP polymorphic code example This article mainly introduces the PHP polymorphic code example, this article uses 2 code examples to demonstrate the PHP polymorphism, needs the friend can refer to the polymorphic definition: only cares about one ...