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?
A constant is dependable. It will not change.
Say for example You are writing a class library that others can use.
Say you want to use Pi to 5 decimal places, and forwhatever reason you don’t want to make it a private variable with a getter.
So you do
Now some guy who is using your class accidently does
Well that will screw everything up.
So instead, you do
Now you know it won’t change and won’t screw stuff up. Plus developers will know that you have defined it that specific value for a reason.