Constants


Hi, in this tutorial i will be showing you how to use Constants.

What is a constant?
If you have ever used actionscript before, you would know that the variables are case sensitive and also dont need anything before them (like a $ identifier used for vars in php). A constant is the alternative to a php variable.

How to define a constant
The function used to define a constant is...

PHP Code
  1. <?
  2. define('CONSTANTNAME', 'Constant value', true);
  3. //parameters are...
  4. // name, value and case_insensitive
  5. ?>


The name of the constant must be put in '' so that the name is defined properley. The constant value can be anything, even a variable and it is optional to set the case_insensitive parameter. The default value for the case_insensitive parameter is false (case sensitive), this can easily be changed by setting the parameter to true.

How to use constants

Constants can be used exactly like variables...
PHP Code
  1. <?
  2. $debug= $_GET['debug']; //not gunna bother processing
  3. define('DEBUG', $debug, true);
  4.  
  5. echo constant('DEBUG'); //echos the constant
  6. //you can also use...
  7. echo DEBUG; //same thing as using constant function
  8.  
  9. if (DEBUG == "no"){
  10. echo "debugging is off";
  11. }elseif (DEBUG == "yes"){
  12. echo "debugging is on";
  13. }
  14. ?>


How would i change the constants value?
Be creative. Use variables? if not you can always use something like...

PHP Code
  1. <?
  2. define('THE_TIME', time()); //time constant
  3. ${THE_TIME} = time()+3600; //changes the time
  4. //but now if you want to echo the constant...
  5. echo ${THE_TIME};
  6. ?>


How do i check if a constant is defined?

To check whether or not a constant is deinfed you will need to use the php defined() function...

PHP Code
  1. <?
  2. if (defined('CONSTANT_NAME'){
  3. //it exists
  4. }else{
  5. //it doesnt exist
  6. }
  7. ?>


Anyway i hope you enjoyed this tutorial and learnt something :P
Thanks!
ilyas-shezad's Avatar
Views:
2,249
Rating:
Posted on Thursday 17th July 2008 at 12:15 AM
darklight19
darklight19's Avatar
At least it's copy & pasta proof. :D
Posted on Wednesday 16th July 2008 at 06:27 PM
ilyas-shezad
ilyas-shezad's Avatar
Just noticed an error in the last pice of php code provided. I missed out a close bracket in my statement.