Forgot Password / Register
Site Statistics
Total Members: 520
Total Tutorials: 242
Newsest User: 8884244477
Todays Unique Hits: 444
0 Users 4 Guests Online

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
3
4
5
6
<?
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'$debugtrue);

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
1
2
3
4
5
6
7
<?
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
1
2
3
4
5
6
7
8
<?
if (defined('CONSTANT_NAME'){
//it exists
}else{
//it doesnt exist
}
?>


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