Question

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?

Was it helpful?

Solution

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

   Class Foo {

       public $pi = 3.14159;
   }

Now some guy who is using your class accidently does

$foo->pi = 4;

Well that will screw everything up. So instead, you do

const $pi = 3.14159;

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top