Page 1 of 1

Constructors and overloading

Posted: Wed Apr 23, 2008 3:45 pm
by Lingultblad
Hello,

I have lately been programming a lot in Java and ASP.NET where you always have several constructors and you use overloading.
I would like to know how this is solved in php?
I have understood that overloading is not permitted and that you are only allowed to have one constructor.

Every answer is appreciated!

Re: Constructors and overloading

Posted: Wed Apr 23, 2008 5:22 pm
by Christopher
Parameters are not typed and can be optional in PHP, and you can get parameters using build-in functions as well, so the discussion is a little bit apples and oranges. The short answer is that you can overload, but it is done in different ways in PHP.

Re: Constructors and overloading

Posted: Thu Apr 24, 2008 2:26 am
by Lingultblad
So how do one work in php?
I don't really need a workaround to how to do things like they are done in java or so, but would rather now how to work properly in php.

Re: Constructors and overloading

Posted: Thu Apr 24, 2008 2:33 am
by Christopher
Say for example you want a function always has a first parameter, but can have second and/or third parameters then do:

Code: Select all

function myfunc($foo, $bar=null, $baz=null) {
You can have any kind of scalar as a default. You can pass any kind of variable you want. Use the var type checking functions to determine the type (is_*()). Or look at the variable parameter list functions:

http://us2.php.net/manual/en/function.func-get-args.php