Constructors and overloading

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lingultblad
Forum Newbie
Posts: 5
Joined: Fri Apr 04, 2008 8:12 am

Constructors and overloading

Post 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!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Constructors and overloading

Post 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.
(#10850)
Lingultblad
Forum Newbie
Posts: 5
Joined: Fri Apr 04, 2008 8:12 am

Re: Constructors and overloading

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Constructors and overloading

Post 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
(#10850)
Post Reply