Question

Basic PHP design questions: I want to define a couple of constants that are accessible to all the files in my website. If I use define() I have to do that for each class which seems silly in that if/when I change that constant for a future release, I'll have to change it in each file. One option is to put it in a file and then require_once that file in all my source files, but that seems excessive too. Is there a place I can define the constant so that it is global across files?

For example:

define('MAX_ELEMENTS', 5);

At some point in the future, I may change this to 6. I use MAX_ELEMENTS in my business logic everywhere.

Was it helpful?

Solution

It's very common to have a single, canonical include file used by all (or most) scripts on your website. PHP even has auto_prepend_file to allow for this.

OTHER TIPS

The way to do it really is to require_once() the file which defines the constant in every file that needs it, and it really isn't uncommon to have a set of includes in every or nearly every file in a PHP application.

If your class hierarchy permits it, a base class can define the class constant, which is inherited by subclasses.

Constants are automatically available in every scope, and apart from the constants defined by php itself, there are no predefined constants. Luckily, php interpreters tend to be very small, and there is absolutely no reason not to include a file constants.php in your project, which you then require_once when it's needed.

The point of a constant is to only be defined once. As such, as you say, you do not define it in every file. Therefore your only choice really is to define it in one file and require_once that file everywhere it's needed. That's not excessive, that's the normal modus operandi.

In addition to the other answers, if your application gets complex enough, consider moving away from using constants to store configuration. They might be fine for now, but what happens if you want to include some code from another library that wants to define a constant by the same name but for a different purpose? Something like Zend_Config may be overkill right now, but keep in mind that constants are very blunt instruments, so it pays to limit their use to truly special cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top