Reputation: 11545
Class constant
class Hello{
const SOME_SETTING = 5;
}
Normal constants
define('HELLO_SOME_SETTING', 5);
To access the class constant I have to call
Hello::SOME_SETTING
To access the normal constant
HELLO_SOME_SETTING
So far both are ok, but what happens if I want to update the value of some constants? I would have to browse .php files, track down each class and modify the constants.
But using normal constants I would just place all defines inside a single config file or something, where I can easily find them when I need to change something.
This is one disadvantage of class constants in my opinion. Are there any advantages?
Upvotes: 1
Views: 181
Reputation: 437336
The main advantage is locality, which affords better organizational structure. If you have a class BufferedReader
that uses a BUFFER_SIZE
constant, it's much better for the constant to be defined alongside the code that uses it.
But using normal constants I would just place all defines inside a single config file or something, where I can easily find them when I need to change something.
That's IMHO the wrong way to use constants (although this practice is quite widespread). A constant is something that, as far as can be foreseen, will not change -- for example, the number of days in a week. What you are describing here is a configuration variable.
Upvotes: 7