|
|
 |
Chapter 13. Constants
A constant is an identifier (name) for a simple value. As the name
suggests, that value cannot change during the execution of the
script (except for
magic constants, which aren't actually constants).
A constant is case-sensitive by default. By convention, constant
identifiers are always uppercase.
The name of a constant follows the same rules as any label in PHP. A
valid constant name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thusly:
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Example 13-1. Valid and invalid constant names |
<?php
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more")
define("2FOO", "something");
define("__FOO__", "something");
?>
|
|
Note:
For our purposes here, a letter is a-z, A-Z, and the ASCII
characters from 127 through 255 (0x7f-0xff).
Like superglobals, the scope of a constant is global. You
can access constants anywhere in your script without regard to scope.
For more information on scope, read the manual section on
variable scope.
You can define a constant by using the
define()-function. Once a constant is defined,
it can never be changed or undefined.
Only scalar data (boolean, integer,
float and string) can be contained
in constants.
You can get the value of a constant by simply specifying its name.
Unlike with variables, you should not prepend
a constant with a $.
You can also use the function constant() to
read a constant's value if you wish to obtain the constant's name
dynamically.
Use get_defined_constants() to get a list of
all defined constants.
Note:
Constants and (global) variables are in a different namespace.
This implies that for example TRUE and
$TRUE are generally different.
If you use an undefined constant, PHP assumes that you mean
the name of the constant itself, just as if you called it as
a string (CONSTANT vs "CONSTANT"). An error of level
E_NOTICE will be issued
when this happens. See also the manual entry on why
$foo[bar] is
wrong (unless you first define()
bar as a constant). If you simply want to check if a
constant is set, use the defined() function.
These are the differences between constants and variables:
Constants do not have a dollar sign ($)
before them;
Constants may only be defined using the
define() function, not by simple assignment;
Constants may be defined and accessed anywhere without regard
to variable scoping rules;
Constants may not be redefined or undefined once they have been
set; and
Constants may only evaluate to scalar values.
Example 13-2. Defining Constants |
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; echo Constant; ?>
|
|
User Contributed Notes
Constants
hafenator2000 at yahoo dot com
21-Apr-2005 05:09
PHP Modules also define constants. Make sure to avoid constant name collisions. There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used. ex. <?php if (! defined("CONSTANT_NAME")) { Define("CONSTANT_NAME","Some Value"); } ?> This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception ex. <?php Define("SITE_CONSTANT_NAME","Some Value"); ?>
Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.
storm
18-Apr-2005 12:54
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:
settings.php
<?php
define('DEBUG',false);
?>
test.php
<?php
include('settings.php');
if (DEBUG) {
}
?>
If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:
settings.php
<?php
define('DEBUG',0);
?>
test.php
<?php
include('settings.php');
if (DEBUG == 1) {
}
?>
Now it works correctly.
Charles
12-Jan-2005 04:50
To clarify from the previous post:
When you define a constant, it becomes fixed at that point and is immutable. You can add variables - but the constant becomes the contents of that variable when the define is evaluated. If you try:
define( "_A_TEXT" , "The value is " . $arr[$i] );
It would be evaluated ONCE with the current value of the $i index of array $arr. As the post pointed out, this is probably not what you want. You can easily create:
define( "_A_TEXT" , "The value is ");
....
echo _A_TEXT . $arr[$i];
Which would give you what you wanted: the constant string with the contents of the array appended.
the_coder at colina2004 dot com
24-Jun-2004 04:42
I'm currently working on a site that has got to have two languages, and I wanted to use define's in functions to make everything simpler.
However, I ran into a problem. PHP doesn't recognize the variable in:
define("constantName", "This is an array variable - {$array[$i][2]}");
I can't use that in a for cycle, like I wanted to:
for ($i = 0; $i < count($array); $i++) {
echo constantName . "<br />"
}
The method I found (I think it's been mentioned before) is to:
define("constantName", "This is an array variable - %s");
And then:
for ($i = 0; $i < count($array); $i++) {
printf(constantName, $array[$i][2]);
}
kumar at farmdev
25-Oct-2003 08:59
before embarking on creating a language system I wanted to see if there was any speed advantage to defining language strings as constants vs. variables or array items. It is more logical to define language strings as constants but you have more flexibility using variables or arrays in your code (i.e. they can be accessed directly, concatenated, used in quotes, used in heredocs whereas constants can only be accessed directly or concatenated).
Results of the test:
declaring as $Variable is fastest
declaring with define() is second fastest
declaring as $Array['Item'] is slowest
=======================================
the test was done using PHP 4.3.2, Apache 1.3.27, and the ab (apache bench) tool.
100 requests (1 concurrent) were sent to one php file that includes 15 php files each containing 100 unique declarations of a language string.
Example of each declaration ("Variable" numbered 1 - 1500):
<?php
$GLOBALS['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>
<?php
define('Variable1' , "A whole lot of text for this variable as if it were a language string containing a whole lot of text");
?>
<?php
$GLOBALS['CP_Lang']['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>
Here are the exact averages of each ab run of 100 requests (averages based on 6 runs):
variable (24.956 secs)
constant (25.426 secs)
array (28.141)
(not huge differences but good to know that using variables won't take a huge performance hit)
ewspencer at industrex dot com
18-Aug-2003 09:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:
define('LOCATOR', "/locator");
define('CLASSES', LOCATOR."/code/classes");
define('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR', LOCATOR."/user");
Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:
require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");
as well as dynamic constructs, typical of value assignment to variables:
$userid = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
The above convention works for me, and helps produce self-documenting code.
-- Erich
php-comment-2003-july-24 at ryandesign dot de
24-Jul-2003 10:04
Late reply to fmmarzoa at gmx dot net: You're better off using sprintf format and defining your strings like this:
define('strArticleDescr', 'Published by %1$s on %2$s in %2$s');
It's more standard than what you're doing. Then instead of outputting it using an eval, do this:
echo sprintf(strArticleDescr, $article_author, $article_date, $article_lang_name');
And even better for i18n and l10n, don't use defines; use gettext. See the PHP manual section on gettext and the GNU gettext website. Gettext requires some modification of the way you think about strings but I find it worthwhile to make that adjustment.
Mike Powell
24-Mar-2003 11:46
In response to the notes above about variable references in constants, double quotes isn't a proper solution because it parses the variable at the time the constant is defined. The desired behavior is to have the variables parsed at the time the constant is referenced, and this behavior can really only be achieved by using eval(), as described above.
gv (at) damnsw (dot) net
05-Nov-2002 11:08
fmmarzoa: In PHP 4.2.2/CLI, I had no problem setting define()'s to the contents of variables:
<?
$foo = "PHP";
define( "bar", "$foo is a good thing." );
print bar;
?>
Will print "PHP is a good thing.".
A notable difference, however, between my example and yours is your use of single-quotes. Strings in single quotes (') will not be expanded:
print '$foo';
Will print '$foo', not the contents of $foo.
http://www.php.net/manual/en/language.types.string.php
--gv
alan at akbkhome dot com
23-Mar-2002 12:08
The __FILE__ constant in 4.2rc1 (CLI) will return the location of script specified to be run, rather than the absolute file.
eg. /usr/bin/phpmole (a softlink to /usr/lib/php/phpmole/phpmole.php)
started like this
bash#/usr/bin/phpmole
the line echo __FILE__ in phpmole.php will output /usr/bin/phpmole - in the CGI it would have returned /usr/lib/php/phpmole/phpmole.php
the workaround is to check for links!!
$f = __FILE__;
if (is_link($f)) $f = readlink($f);
katana at katana-inc dot com
25-Feb-2002 02:53
afuse at yahoo dot com
11-Jun-2001 01:42
The pre-defined constant '__FILE__' does not work in same way at every version of PHP.
Some version of PHP has the relative path, and some other has the absolute path on __FILE__ constant..
Please be carefull in use..
[PS]
I have not tested at all versions of PHP but the version of 4.04pl.. and 4.05 are certainly not working in same way.. If you want to see that bug(?), I can show you an example.
silvein at sonique dot com
23-Jan-2001 08:54
It may be useful to note that, in php4 (what version this started I don't know, but it didn't do it before we upgraded to php4) __FILE__ will follow symlinks to the origional file.
tom dot harris at home dot com
04-Aug-2000 08:44
To get a full path (the equivalent of something like "__PATH__") use
dirname($SCRIPT_FILENAME)
to get the directory name of the called script and
dirname(__FILE__)
to get the directory name of the include file.
| |