Trying to figure out whether PHP supports features like method overloading, inheritance, and polymorphism, I found out:
- it does not support method overloading
- it does support inheritance
but I am unsure about polymorphism. I found this Googling the Internet:
I should note that in PHP the polymorphism isn't quite the way it should be. I mean that it does work, but since we have a weak datatype, its not correct.
So is it really polymorphism?
Edit
Just can't quite place a definite YES or NO next to PHP supports polymorphism
. I would be loath to state: "PHP does not support polymorphism", when in reality it does. Or vice-versa.
Polymorphism can be implemented in the following methods:
method overriding
- normal pretty was as abovemethod overloading
You can create an illusion of method overloading by the magic method __call():
Expln:
In php
, we are actuallyworking under the hood
to give the desired behaviour and giving the feelingof method overloading
You can label it all you want, but that looks like polymorphism to me.
You can still override methods, just not overload them. Overloading (in C++) is where you use the same method name for multiple methods, differing only in number and types of parameters. This would be hard in PHP since it's weak-typed.
Overriding is where the sub-class replaces a method in the base class. Which is really the basis for polymorphism, and you can do that in PHP.
__call()
and__callStatic()
should support method overloading. More on this is available in the manual. Or what exactly are you after?UPDATE: I just noticed the other replies.
For another way to overload a method, consider the following:
Certainly not pretty, but it allows you to do virtually whatever you want.
For what I’ve seen here php do not support polymorphism, nor overloading methods. You can hack your way to actually get close to both of these oop functionalities, but they are far from the original purpose of it. Many of the examples here either are extending a class or creating a hack to emuluate polymorphism.
PHP allows for polymorphic code that would generate an compile error in other languages. A simple illustrates this. First C++ code that generates an expected compile error:
The C++ compiler will issue this error message for the line
db.whoami()
because Base does not have a method called whoami(). However, the analogous PHP code does not find such errors until run time.
The foreach loop works with the output
Not until you call test($b) and pass an instance of Base will your get a run time error. So after the foreach, the output will be
About the only thing you can do to make the PHP safer would be to add a run time check to test if $b is an instance of the class you intended.
But the whole point of polymorphism is to eliminate such run time checks.