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
<?
define('CONSTANTNAME', 'Constant value', true);
//parameters are...
// name, value and case_insensitive
?>
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
3
4
5
6
7
8
9
10
11
12
13
14
15
<?
$debug= $_GET['debug']; //not gunna bother processing
define('DEBUG', $debug, true);
echo constant('DEBUG'); //echos the constant
//you can also use...
echo DEBUG; //same thing as using constant function
if (DEBUG == "no"){
echo "debugging is off";
}elseif (DEBUG == "yes"){
echo "debugging is on";
}
?>
How would i change the constants value?
Be creative. Use variables? if not you can always use something like...
PHP Code
<?
define('THE_TIME', time()); //time constant
${THE_TIME} = time()+3600; //changes the time
//but now if you want to echo the constant...
echo ${THE_TIME};
?>
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
<?
if (defined('CONSTANT_NAME'){
//it exists
}else{
//it doesnt exist
}
?>
Anyway i hope you enjoyed this tutorial and learnt something :P
Thanks!