Polymorphic definition: Only one interface or base class is concerned, but not the specific class of an object. (same type, different result)
Here are two examples:
First, we found that the base class defines the criteria, and subclasses perform the implementation of the self rule. This is a requirement for polymorphism. At the same time, it is satisfying to rewrite; in fact, this is a different kind of performance; there is no strict satisfaction with an interface, or base class programming. Because you call the time is not Stu->showgrade () but their own methods;
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 show ';
}
function doit ($obj) {
if (Get_class ($obj)!= "Stu") {
$obj->showgrade ();
}
}
Doit (new Xiaoli ());
Doit (new xiaomin ());
The second example: the Dovoice parameter stipulates the $obj as animal, the consciousness is to accept the implementation class object with the interface. The upward transition. This is consistent with the same type, different results, this is polymorphism;
Actually in Java it would be animal a = new dog (); Because PHP is a type language. There is no object transformation mechanism.
Interface animal{public
function Voice ();
}
Class Cat implements animal{public
function voice () {
echo "miao~~~<br>";
}
}
Class Dog implements animal{public
function voice () {
echo "Wang ~~~<br>";
}
}
function Dovoice (animal $obj) {
$obj->voice ();
}
Dovoice (New Dog ());
Dovoice (New Cat ());