I will be talking about using namespaced PHP classes with static properties for configuration. Since my use was in relation to Symfony, it is important to note that the Config component should be used for everything possible, but that it can’t be used before it is instantiated.
Reasons to use namespaced static class properties for configuration:
- A class can be defined in a file. When that file is included from elsewhere, the class is defined.
- Once a class is defined, it is accessible anywhere after that point, regardless of scope. Like a superglobal.
- Statics are variables set on a class rather than on an instance and can be accessed directly from the class. This means no variables outside of the class need to be set to work with the variables. Like a superglobal singleton.
- Statics are not static and can be modified just like any other variables.
- Static methods can control access and provide other behaviors you may want for working with your configuration.
- Namespaces help prevent collisions of class names by essentially adding characters to a class name that make it less likely to be used elsewhere. With psr-0 / psr-4 autoloaders, the namespaces should be well controlled.
- Variables can’t be namespaced, so classes (or constants or functions) are the only way to take advantage of their benefits.
- Using constants and functions inside of a namespace is similar to static properties and methods of a class, except the constants are immutable and have limited data types, and there aren’t the niceties like
selffor the functions.
- Being in PHP (as opposed to some config file format) allows use of
__DIR__(my primary need was for storing paths, and it wouldn’t be ideal to have to put in the full filesystem paths to things), string concatenation and other operations, and any other PHP behavior or values desired.