Reputation: 141
In C++, if I want to use Polymorphism, I would create a parent class and then derive many child classes from the parent class, and then I would be able to assign an address of a child class object to a pointer variable of the parent class.
For example: say that I have a parent class called Animal
, and then I derived two child classes from Animal
, which are Dog
and Cat
, and the three classes have a method called speak()
.
Now I can create a function that takes Animal*
as argument:
void foo(Animal* animal)
{
animal->speak();
}
And do the following:
Cat *cat = new Cat();
Dog *dog = new Dog();
foo(cat);
foo(dog);
But in PHP, a variable can be of any type, so even if I don't have a parent Animal
class and only have a Cat
and a Dog
class, I can still do the following:
function foo($animal)
{
$animal->speak();
}
$cat = new Cat();
$dog = new Dog();
foo($cat);
foo($dog);
So is it still called Polymorphism when not using a parent class?
Upvotes: 0
Views: 180
Reputation: 67723
The sort of polymorphism you're describing in C++ is subtyping (the third in the list of three distinct meanings in this linked Wikipedia article).
This is also described (at least in statically-typed languages like C++) as dynamic polymorphism since the point is that the "dynamic" (runtime) type of your object varies from the "static" compile-time type of the interface.
What you're discussing in PHP is duck typing, which is essentially a form of parametric polymorphism.
This is roughly equivalent to the static polymorphism you get from templates in C++, although the implementation is obviously very different.
Upvotes: 1
Reputation: 17415
Polymorphism is a concept that's pretty abstract and in particular independent of any particular implementation. In that sense, yes, your code uses polymorphism.
Now, concerning your comparison with C++, you are comparing apples with oranges here. The following piece of PHP is much closer to the C++ code:
function foo(Animal $animal)
{
$animal->speak();
}
On the other hand, you can also adjust the C++ code:
template<typename animal_type>
void foo(animal_type& animal)
{
animal.speak();
}
Note that I have fixed the non-idiomatic use of pointers by your version, but the important part is that the function is now a template.
Upvotes: 0