Hudzilla.org - the homepage of Paul Hudson
Contents > Simple variables and operators Wish List | Report Bug | About Me ]

3.11     Constants: define(), defined(), and constant()

This is NOT the latest copy of this book; click here for the latest version.

If you find yourself setting a variable for convenience and never changing it during a script, the chances are you should be using a constant instead. Constants are like variables except that once they are defined they cannot be undefined or changed - they are constant as the name suggests. In many languages, constants are faster than variables and so are recommended, but this is not the case as much in PHP - although they are a small amount faster, the primary advantage to using constants is the fact that they do not have a dollar sign at the front, and so are visibly different from variables. Furthermore, constants are automatically global across your entire script, unlike variables.

To set a constant, use the define() function - it takes two parameters, with the first being the name of the constant to set, and the second being the value to which you wish to set it. For example, this following line of code sets the variable CURRENT_TIME to be the return value of the time() function, then prints it out:

define("CURRENT_TIME", time());
print
CURRENT_TIME;

Note that it is not $CURRENT_TIME or Current_Time - constants, like variables, are case sensitive, but unlike variables they do not start with a dollar sign. You can change this behaviour by passing true as a third parameter to define(), which makes the constant case-insensitive:

define("CURRENT_TIME", time(), true);
print
Current_TiMe;

There are two helpful functions available for working with constants, and these are defined() and constant(). The defined() function is basically the constant equivalent of isset(), as it returns true if the constant string you pass to it has been defined. For example:

define("CURRENT_TIME", time(), true);
if (
defined("CURRENT_time")) {
    
/// etc
}

Note that you should pass the constant name into defined() inside quotes.

Finally, constant() is a function that might seem redundant at first, but it makes sense if you give it a chance: it returns the value of a constant. Now, I realise that you can just get the value of a constant by using it directly, e.g. "print MY_CONSTANT;", but how would you accomplish that if you did not know the constant's name? If you were working with a variable, you could use a variable variable, but this is not possible with constants - hence the constant() function.

<?php
    define
("Current_Time", time(), true);
    
$somevar = "CURRENT_TIME";
    print
constant($somevar);
?>




<< 3.10 References   3.11.1 Pre-set constants >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 29 Aug 2008

please tell me the way to protect pages using define?

like this
defined( 'NSP' ) or die( 'Direct Access to this location is not allowed.' );

yorris@gmail.com - 29 Aug 2008

Ranjang, I think you're trying to match the $x = "A" (in case switching)
with $x = "a" which is not equal. Take a look at the codes below:

<?php
define ("A", 5, true);
define ("B", 6, true);

$x = "a";

switch ($x){
case "a": print constant($x);
break;
case "b": print constant($x);
}
?>

Houdini - 29 Aug 2008

Constants do not need quoted also do not use the word constant just tell the acript to print or echo the CONSTANT
also the case must be a value not the constant or variable itself you you have two choces 5 or six so this will work, of course it has no real value but it does work.
define("A",5,true);
define("B",6,true);
$x= B;

switch($x){

case "5":
print A;
break;
case "6":
print B;
break;

}

ranjangoyal2004@yahoo.com - 29 Aug 2008

Hi,

I tried this and it doesn't print.Why?


define("A",5,true);
define("B",6,true);

$x="a";

switch($x){

case "A":
print constant("A");
break;
case "B":
print constant("B");
break;

}

A PHP User - 29 Aug 2008

thanks Luis
it makes sense now
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
:-)

A PHP User - 29 Aug 2008

In this example:
<?php
define( "NUMBER_9", 9 );
print NUMBER_9;
?>

The result will be 9, which is correct. To print a new line i would use the new line character ("\n") and quotes ("print NUMBER_9 \n";), right?

But after the modification and re-executing the example the result will be "NUMBER_9", not 9 as i would expect. So i ask, to print the value of a constant plus new lines or other chars i need to assign the constant`s value to a variable first and then print the value of the variable?

thanks!

MDK - 29 Aug 2008

It's probably the number of milliseconds since a specified date/time (something like Midnight 1st Jan 1970).

webmaster@dezinepros.com - 29 Aug 2008

okay, I got it - but what the devil is the number it prints out? It doesn't look like time...??

webmaster@dezinepros.com - 29 Aug 2008

I'm not sure on this one...even without the typos, when I try to define two constants I get a parse error referring to the first line of the second define statement. "unexpected T_CONSTANT_ENCAPSED_STRING"

A PHP User - 29 Aug 2008

Like the author said, you have to actually play with the code to get the most out of it. I was about to move on to the next chapter thinking this function sucked. But it isn't "redundant"... thanks for stressing that.

A PHP User - 29 Aug 2008

Here is my example:

<?php
define("Current_Time1", time(), true);
$somevar = "CURRENT_TIME1";
print constant($somevar);

define("Current_time", time(), true);
$somevar2 = "CURRENT_TIM";
print constant($somevar2);

print current_tim;
?>

Luis - 29 Aug 2008

Keith, I hope you're the type of guy that checks if their questions are answered. I was confused like you so I decided to play with the example a little more.

The part that you missed is that a constant is defined as a string. With that said, if you do not know the name of the constant then when you try and print it out you'll just print out your typo "current_tim" instead of an error which costant() would provide.

I know you're probably striking your forehead about now. I didn't realize this until I was about to post agreeing with you.

Keith - 29 Aug 2008

Perhaps I am missing something. Aren't we using the name of the constant in that last example?

I read the part before about referencing and I must have missed something. If we do not know the name of the constant CURRENT_TIME then how can he assign it to $somevar?

A PHP User - 29 Aug 2008

^

A PHP User - 29 Aug 2008

I disagree, I think a constant should be really set aside for those immutable constants in a script; the vaule of pi for example. Recording the current time is really variable - hence the name current!

A PHP User - 29 Aug 2008

If you want a constant to mark the time a script or event began it makes perfect sense.

A PHP User - 29 Aug 2008

Why use something like time to explain constants?

The only thing constant about time is that it's constantly changing.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow