Are PHP global constants a good modern development practice? Are PHP global constants a good modern development practice? php php

Are PHP global constants a good modern development practice?


In my opinion, constants should be used only in two circumstances:

  • Actual constant values (i.e. things that will never change, SECONDS_PER_HOUR).
  • OS-dependent values, as long as the constant can be used transparently by the application, in every situation possible.

Even then, I'd reconsider whether class constants would be more appropriate so as not to pollute the constants space.

In your situation, I'd say constants are not a good solution because you will want to provide alternative values depending on where they're used.


These constants smell like global variables, and they're referenced directly […]. Would it be reasonable to copy these values into an object and […] convey them via dependency injection?

Absolutely! I would go even further and say even class constants should be avoided. Because they are public, they expose internals and they are API, so you cannot change them easily without risking breaking existing applications due to the tight coupling. A configuration object makes much more sense (just dont make it a Singleton).

Also see:


To answer this question it is important to discuss the style of code being written.

PHP 5 includes a number of useful OOP features, one of which is class constants. If you're using an object oriented approach, rather than polluting the global namespace, or worry about overriding common constants, you should use class constants.

FOO_BAR could be FOO::BAR in the end, it comes down to the scope of where you want the constant defined.

If you're writing a more procedural style program, or mixing procedural with some classes, global constants aren't an issue. If the code you're working on is becoming unmanageable due to the constants you're using, try changing things around. Otherwise, don't worry about it.

Additionally, class constants wont allow you to use function return values, global constants will. This is great when you have a value that wont ever be changed throughout the scope of the program, but needs to be generated.