Page 1 of 1

Why there is no cunstructor overloading in PHP

Posted: Tue Feb 03, 2009 5:03 am
by plamen_t
Hi all,

I know that there is no constructor overloading as it is in the other OO languages as C++ or Java. I know how we can simulate overloading and some tricks to deal with that situation. But my question is not how to deal with that but why there is no constructor overloading? What is the reason for that. I suppose that the reason is because the interpreter is unable to determine the appropriate constructor to use only by the type and the number of the parameters. Any ideas?

Thanks.

Re: Why there is no cunstructor overloading in PHP

Posted: Tue Feb 03, 2009 5:10 am
by mickeyunderscore
I'd guess that it's due to PHP being loosely typed, you cannot declare parameter types (other than array or a particular class instance) so there wouldn't be any way to distinguish between the different constructors other than number of variables, which would make overloading pretty limited anyway. I have found that setting default parameters usually makes up for the lack of overloading.

Adding this example because I'm not sure I was very clear:

Code: Select all

$boolean = false;
$string = '3';
$int = 3;
$float = 3.3;
$boolean = $string * $int * $float;
echo $boolean;
PHP typecasts everything for you, as you can see from the above, so the need for method overloading is far less. Needless to say, Java would not like this at all.