What, exactly, is the purpose of using constants (in PHP)? I understand how they work, but in which circumstances are they preferable over, say, a global variable? If anything, wouldn't variables be more flexible because they can be placed inside strings?
I've searched the web, but all I've found is definitions--not actual reason for using one or the other. Can anyone help me to understand the benefits of using one over the other?
in which circumstances are they preferable over, say, a global variable?
Constants don't change. Immutable global state would be preferred over its mutable counterpart; in that way, your state is defined in one location and never changes over the course of your script. Barring the use of runkit your code will not be able to change the state in some ways that you didn't expect.
Also, global variables must be declared inside functions by using the global keyword, though technically that declaration, albeit more type-work is better than assumed global I suppose :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With