Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Purpose of Constants?

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?

like image 358
Nathanael Avatar asked Nov 29 '25 08:11

Nathanael


1 Answers

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 :)

like image 162
Ja͢ck Avatar answered Nov 30 '25 23:11

Ja͢ck



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!