Overloading Constructors in PHP

php


Sorry, my fellow PHPeople, but as of today of me writing this (July 23, 2016), PHP (Version 7) does not support the overloading of constructors.

I'm not knocking PHP in any way. I'm the biggest PHP fan. Most of this website was written in PHP, but it doesn't yet support the overloading of constructors.

I tried running a program in which I had 2 constructors (__construct methods). The 2 methods had different parameters or arguments. However, what happened was the program output a fatal error, such as shown below.

Fatal error: Cannot redeclare vehicles::__construct()

This was the complete program that I ran, shown below.



You can see that I have 2 constructors (__construct methods) in the class vehicles. Each constructor has different parameters.

However, PHP outputs that you can't redeclare the __construct method within a given class, meaning you cannot overload constructors.

So PHP, though it has great object oriented ability and has come a long way from PHP4 to PHP5, it does not yet have the OOP capability of Java, for instance, which does support constructor overloading.

But again, this may change in future versions and I'm almost sure it will be updated.

However, as of now, it does not yet support constructor overloading directly. I'm not sure if there's any ways or tricks around it. I don't know of any. But as of direct constructor overloading, PHP does not yet support this.

Note: If you are reading this article and PHP has added functionality so that constructors can be overloaded, please write a comment below and I'll get to it and update this article. Thank you. It would be much appreciated.


Related Resources

How to Create a Final Class in PHP




HTML Comment Box is loading comments...