Optional constructor parameters

Posted on 10 Mar 2010 by Luke Ehresman

One thing that really irks me about PHP is the way parameters are passed into functions and constructors. A typical constructor will look like this:

$col = new Column($id, $label, "50%", true, false);

While that’s nice and compact, it’s impossible to read. Using some context, I might be able to figure out the purpose of the variables, but unless I’m familiar with this function, I have no idea of the purpose for the “true” and “false”.

It hit me this week that I should start using a sweet idea from the MooTools playbook. Many object constructors in MooTools take an “options” parameter that is a hash of parameters. The class itself has default values for all of these options, so when you’re passing them into the constructor you can pick and choose which ones you want and set values for them. We can do the exact same thing in PHP.

My proposed solution for unreadable and long sets of parameters is to do something like this:

See how much more readable and versatile this is? There could be another option called “type” that defaults to “text”. But since I don’t want to change the default, I don’t need to include it here. For required parameters (like “label” and “name”), simply throw an exception if they are not included in the option list.

As I see it, here are the benefits:

Readability - It’s easy to glance at this and see the purpose of every parameter.

Forward compatible - If you add another option to the constructor down the road, as long as you provide sensible defaults, this is forward compatible. You won’t have to go through your code and add the 6th parameter to every Column instantiation.

Flexibility - Developers don’t need to remember the order of the parameters since they can be added in any order.

Tebros Systems is a software incubator that creates
custom and hosted software solutions.

We are eager to solve difficult problems, create usable web apps, and make
your idea become reality. We have a wide range of experience from web
development to database optimization to usability analysis and more. Contact
us with your idea. We’ll walk you through a feasibility assessment and help
your project come to life.