Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How does one define a constant that is accessible by multiple files?

Tags:

php

constants

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.

like image 782
tterbeg Avatar asked Jan 19 '26 00:01

tterbeg


1 Answers

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.

like image 100
Michael Berkowski Avatar answered Jan 21 '26 13:01

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!