Tweeted twitter.com/#!/StackProgrammer/status/440300895524651008
2 edited tags
| link
1
source | link

Constants vs public properties for configuration

My application has a few high level configuration options such as directories which will be used for various things, database connection information and a few other settings which are required for the application to run.

I'm debating with myself whether or not constants are better than variables for this purpose and would like some input.

By having:

 $config = new Config;
 new Whatever($config->foo, $config->bar);

Instead of:

new Whatever(Config::FOO, Config::BAR);

I get the power of polymorphism, I can quickly swap between configuration settings by instantiating $config as a different class with the same class members.

There's obviously a trade-off here. Anything which needs the config options must instantiate a $config object, using memory and creating extra code as well as making it so the config options are no long immutable.

The immutability problem could by solved with a method e.g. $config->get('Foo'); so that is potentially a non-issue, although it does add to verbosity and a method call is more expensive than reading a constant or variable.