PHP: define - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

defined constant

Last updated: Sat, 27 Jan 2007

view this page in

# define

(PHP 3, PHP 4, PHP 5)

define -- Defines a named constant

## Description

bool define ( string name, mixed value [, bool case_insensitive] )

Defines a named constant at runtime. See the section on constants for more details.

The name of the constant is given by `name`; the value is given by `value`.

The optional third parameter `case_insensitive` is also available. If the value `TRUE` is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.

Пример 1. Defining Constants

`<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."
?>`

Возвращает `TRUE` в случае успешного завершения или `FALSE` в случае возникновения ошибки.

See also defined(), constant() and the section on Constants.

add a note User Contributed Notes
define
alf
31-Jan-2007 03:10
`Couldn't see this beeing brought up, so I write it here
so all can be clear:
<?php
define('test', 8);
$foo[8] = "debug 1";
$foo['test'] = "debug 2";
print $foo[test]; // "debug 1"
print $foo['test']; // "debug 2"
?>
What happens when we use a string variable as key?
<?php
$str = "test";
print $foo[$str];
?>
One (wrong) way of reasoning:
=> $str outputs just test (without quotes)
=> $foo[$str] should then translate to $foo[test]
=> $foo[test] whould translate to $foo[8] (because test is a defined constant)
=> output should then be "debug 1"
This is wrong! ..but I'm sure I'm not the only one who thought about this.. ;)
Both $foo[$str] and $foo["$str"] outputs "debug 2"`
kangaroo232002 at yahoo dot co dot uk
21-Jan-2007 10:49
`I believe that using the case-insensitive boolean (e.g. define("CONST_VAL", 1, false)) doesn't work when trying to use the function constant() -- e.g.
<?php
$var = "const_val";
echo constant($var);
?>
throws an error. Works instead when using strtoupper() on $var.`
admin at automapit dot com
14-Jan-2007 02:27
`off-topic, but in response to Kangaroo...
Apache can hide the non-.php files such as .inc or .ini by using...
<Files ~ "\.inc">
Order allow,deny
Deny from all
Satisfy All
</Files>`
kangaroo232002 at yahoo dot co dot uk
09-Jan-2007 01:08
`It should be noted that putting your settings in a non-PHP file (for example, mysql connection settings) as in the XML example can have quite significant security issues, that's why I prefer to have the parser hide it from potential visitors by using define rather than write settings in an INI file.`
stangelanda at arrowquick dot com
31-Dec-2006 06:59
`An improvement on the function from bobbykjack at yahoo dot co dot uk on the concept by richard dot quadling at bandvulc dot co dot uk:
<?php
function adefine($constant_name, $value=null) {
static $increment = 0; // 1 for bitmask
if (is_null($value)) {
define($constant_name, ++$increment); // $increment=$increment<<1 for bitmask
} else {
define($constant_name, $value);
if (is_numeric($value)) {
$increment = $value;
}
}
}
?>
If you pass it a second argument it defines it normally, and resets the increment if the value is numeric. This way the function can replace define, and you can reset the counter for a new set of constants.
<?php
adefine ('RULE_CALLBACK_FORMAT', 1); // 1
adefine ('RULE_CHANGE_CALLBACK_ON_ERROR'); // 2
adefine ('RULE_CHANGE_COMPARE_DATE'); // 3
adefine('KEYWORD', 'hodgepodge'); // hodgepodge <-- defined normally
adefine ('RULE_CHANGE_ON_DATE'); // 4
adefine ('ERROR_DESC', 1); // 1 <-- Counter reset
adefine ('ERROR_EXPECTED_RESULT'); // 2
?>`
mort
28-Dec-2006 02:29
`define gives also quite nice tool to prevent including classes two times:
<?
if(!defined("MYCLASS_PHP")) {
define("MYCLASS_PHP", null);
class MyClass
{
/* class body */
}
} // endif
?>`
sean at syoft dot com
30-Jul-2006 11:21
`I typically use
define('CONSTANT',serialize($value));
to store arrays in constants and then just unserialize as needed:
if(in_array('val',unserialize(CONSTANT))) {}
Didn't see this mentioned here previously.`
m dot blanquett at gmx dot de
25-Jul-2006 07:35
`If u have a bunch of definitions to handle, and want them to be really easy configureable, use this:
definitions.xml:
<definitions>
<definition>
<name>PROGRAM_NAME</name>
<value>Foo Bar</value>
</definition>
<definition>
<name>PROGRAM_VERSION</name>
<value>0.0.1</value>
</definition>
</definitions>
<?php
$defs = simplexml_load_file('definitions.xml');
foreach($defs->definition as $def) {
eval("define('{$def->name}', '{$def->value}');");
}
?>
Of course you can alter the xml format as you please, maybe like this (be aware, that you then need to change the php code to the new layout of the simple xml object.
<definitions>
<def name="PROGRAM_NAME" value="Foo Bar" />
<def name="PROGRAM_VERSION" value="0.0.1" />
</definitions>`
xademax at gmail dot com
04-May-2006 05:46
`<?php
class Define
{
var $Name;
var $Func;
function Define($Name, $Func)
{
$this->Name = $Name;
$this->Func = &$Func;
}
}
$DEFINES = array();
function set_define($Name, $Value, $Args)
{
global $DEFINES;
foreach($DEFINES as $DEFINE) if($DEFINE->Name == $Name) return false;
$DEFINES[] = new Define($Name, create_function($Args, 'return "' . $Value . '";'));
}
function get_define($Name, $Args = NULL)
{
global $DEFINES;
foreach($DEFINES as $DEFINE) if($DEFINE->Name == $Name)
{
$Func = $DEFINE->Func;
return eval('return $Func(' . implode(",", $Args) . ');');
}
return false;
}
?>
<?php
set_define("ERROR", 'There was an error : $error\n', '$error');
echo get_define("ERROR", array("pouet"));
?>
This Exemple will show :
There was an error : pouet`
RQuadling at GMail dot com
08-Mar-2006 01:18
`Yes. I did mistyped the base value.
And I only use the constants in their text form (the whole point of them really).
They are actually used in a XML structure as tags (now). Previously they where the keys in a massive multi-dimensional array.
If I added a new constant, nothing changed in terms of the data storage. If I removed one though, the data would not work and neither would the program using the data. Which is good news.`
bobbykjack at yahoo dot co dot uk
18-Feb-2006 12:12
`benjamin, I recognise your warning, but surely a key point of constants is that their values should NOT be referenced anywhere other than their definition.
richard, your solution could be made slightly safer with the use of a function for this process, e.g.
<?php
$iRuleVal = 0;
adefine ('RULE_CALLBACK_FORMAT');
adefine ('RULE_CHANGE_CALLBACK_ON_ERROR');
adefine ('RULE_CHANGE_COMPARE_DATE');
// etc.
// 'a' for auto
function adefine($constant_name)
{
global $iRuleVal;
if (defined($constant_name))
{
// error handling should go here
return;
}
// good idea to use pre-increment; avoids use of 0
// and associated equality issues with empty string
// via type conversion
define($constant_name, ++$iRuleVal);
}
?>
I think you also misnamed the original local variable - it should be $iRuleVal.`
benjamin at metaconsult dot fr
07-Dec-2005 04:59
`a warning for richard below (and who is reading the advice below).
When you remove constant in your pool, but already stored some of those values in a database or somewhere else as reference, you will surely mess up your application data !
So such an auto-definition for your constants is useful when you don't store those values anywhere else !`
richard dot quadling at bandvulc dot co dot uk
01-Dec-2005 03:40
`In trying to remove magic numbers from my code, I often use sets of defines. Some sets get quite big.
I sort my defines so that they are alphabetically arranged - for me this is easier.
The issue now comes as to what is the next available number or what happens to the number sequence if I remove a define.
My solution is to use the following mechanism.
<?php
$iRuleBase = 0;
define ('RULE_CALLBACK_FORMAT', ++$iRuleVal);
define ('RULE_CHANGE_CALLBACK_ON_ERROR', ++$iRuleVal);
define ('RULE_CHANGE_COMPARE_DATE', ++$iRuleVal);
define ('RULE_CHANGE_OLD_COLUMN', ++$iRuleVal);
define ('RULE_CHANGE_ON_DATE', ++$iRuleVal);
define ('RULE_DESC', ++$iRuleVal);
define ('RULE_EXPECTED_RESULT', ++$iRuleVal);
define ('RULE_LIMIT_TO_PERIOD', ++$iRuleVal);
define ('RULE_MATCH_ARRAY', ++$iRuleVal);
define ('RULE_MATCH_COLUMN', ++$iRuleVal);
define ('RULE_MESSAGE', ++$iRuleVal);
define ('RULE_REGEX', ++$iRuleVal);
?>
I no longer need to know ANY of the magic numbers. I can add and remove them at will and the code will show errors for the missing ones as the constant will be undefined. Much better than using the number and forgetting what entry 6 is.
You also have the value of $iRuleVal to indicate the next define if needed.
The defines then work like ...
<?php
$aGlobalValidationDefinitions = array(
'CH_SORT' => array
(
RULE_DESC => 'Contract on Cost Header / Project must match the Contract on the order.',
RULE_MATCH_COLUMN => 'POH_CONTRACT',
),
'CH_STATUS' => array
(
RULE_CHANGE_CALLBACK_ON_ERROR => 'dataentryValidateChanges',
RULE_CHANGE_COMPARE_DATE => 'POH_DATE_AUTH',
RULE_CHANGE_OLD_COLUMN => 'OLDSTATUS',
RULE_CHANGE_ON_DATE => 'VSC_DATECHANGED',
RULE_DESC => 'Vehicle Status must be A - Active or R - Reopened.',
RULE_LIMIT_TO_PERIOD => 'D',
RULE_REGEX => '^(?=[AR])(.)$',
),
'POD_COSTHEADER' => array
(
RULE_DESC => 'Must not start with "UNKNOWN".',
RULE_REGEX => '^(?!UNKNOWN)(.*)$',
),
);
?>
No magic numbers. You can add or remove defines without ever worrying about breaking the code and you never have 2 defines with the same value!`
some at user dot com
30-Nov-2005 10:46
`My hack at constant arrays :
function carray($const = null, $index = null)
{
static $carrays;
if ($const === null)
{
$i = count($carrays);
$carrays[$i] = $index;
return $i;
} else
{
return $index === null ? $carrays[$const] : $carrays[$const][$index];
}
}
function aconst()
{
$args = func_get_args();
if (count($args) == 1 && is_array($args[0]))
{
return carray(null, $args[0]);
} else
{
return carray(null, $args);
}
}
Use like this:
define('NRWORDS', aconst('zero', 'one', 'two', 'three'));
define('STUNT_DESC', aconst(array(
STUNT_TWOWHEELS => 'Two wheels',
STUNT_WHEELIE => 'Wheelie',
STUNT_STOPPIE => 'Stoppie'
)));
print(carray(NRWORDS, 2));
print(carray(STUNT_DESC, STUNT_WHEELIE));
$arr = carray(STUNT_DESC);
print_r($arr[STUNT_STOPPIE]);
bvr.`
IK
15-Nov-2005 06:42
`[Editor's Note: Obviously, constants cannot be redefined. That is the meaning of a constant.]
Just a quick note.. If a constant is once defined, any subsequent attempts to define it once again are ignored.
<?
define('WHAT_DID_YOU_EXPECT', 'First');
define('WHAT_DID_YOU_EXPECT', 'Second');
echo WHAT_DID_YOU_EXPECT
?>
Outputs 'First'.
I really thought I have gone mad when I saw just the last two lines of code (the first one was in another file) and it was echoing 'First'..`
dsan at pml dot ac dot uk
08-Apr-2005 08:17
`Just to clarify what 'david at nospam webgroup dot org' said:
${} is actually the syntax for 'variable variables'.
So in this specific case:
Starting with the line:
${MY_CONST} = serialize(array('foo' => 'bar'));
PHP will expand the constant and use it as the name of the variable:
$test = serialize(array('foo' => 'bar'));
So in fact there is no assignment to a constant (which would defy the definition of 'constant') but instead an assignment to a variable named by the _value_ of the constant.`
david at nospam webgroup dot org
31-Mar-2005 03:14
`To the comment posted by Raphael Crawford Marks:
You're actually manipulating the variable $test. The value of a constant obviously cannot be changed after it is set: hence the term constant. Try setting $test to something first, then running your code. It *WILL* be clobbered.`
Raphael Crawford-Marks
10-Mar-2005 11:28
`Notes on using serialize to store an array in a constant:
<?php
define('MYCONST','test'); //define constant with junk value
${MYCONST} = serialize(array("foo" => "bar")); //change value to serialized array
echo "constant: ".${MYCONST};
echo "<br>";
$unserialized = unserialize(${MYCONST}); //unserialize
echo "unserialized: ".$unserialized['foo'];
?>
Note that you have to use ${} around the constant name for this to work.`
11-Feb-2005 08:45
`Better pack with define() for all who really miss Java package management:
Use this "manifest.php" on very first script start or copy it to your config.somehow.php.
<?php
$__packages = array(
"org.ilove.java.more",
"org.ilove.python.too",
"net.php.isok"
);
define("C_IS_WINDOWS", false);
define("C_DIR", (C_IS_WINDOWS ? "\\" : "/"));
define("C_PATH_ROOT", str_replace("/", C_DIR, $_SERVER["DOCUMENT_ROOT"]).C_DIR);
define("C_PATH_CORE", C_PATH_ROOT."core".C_DIR);
define("C_PATH_CLASS", C_PATH_CORE."classes".C_DIR);
define("C_APPLICATION_BASE", C_PATH_CORE.C_DIR."application".C_DIR);
$total_packages = 0;
$i = sizeof($__packages);
while($i-- > 0) {
$tokens = explode(".", $__packages[$i]);
$j = sizeof($tokens);
while($j-- > 0) {
$token = strtolower(trim($tokens[$j]));
if(strlen($token) > 0 && !defined($token)) {
define($token, ($j == 0 ? C_PATH_CLASS : "").$tokens[$j].C_DIR);
$total_packages++;
}
}
}
define("C_PACKAGE_COUNT", $total_packages);
?>
With restrictions on non-package constants, you now can call your files like that:
<?php
require_once org.ilove.java.more."Than.php";
?>
Regards
Robi`
tech at litigationdataservices dot com
25-Jan-2005 01:05
`If your oft-used array is already defined, but the key value doesn't start at ['0'], --for example if you need an array of state names conforming to GIS codes, it's far easier to define the array in a low-level class and call it by
$classname->states[$STATEID];
than it is to try to define it as a constant or use an function to call it later from a free-standing array. It's also useful to do it this way when all you want to do is recall a fixed array value, but don't necessarily want to hit the database just to get it.`
technopasta at yahoo dot com dot au
02-Jan-2005 05:55
`You can't use arrays in constants, so I came up with this two line function to get around it.
<?php
function const_array($constant) {
$array = explode(",",$constant);
return $array;
};
?>
So now if you define a constant like
<? define('myconstant','item1,item2,item3') ?>
and then use my function
<? $myarray = const_array(myconstant); ?>
$myarray will now contain an array with
item1
item2
item3
Hope this is useful for someone...`
konstantin #at schukraft #dot org
22-Sep-2003 03:13
`Constants MUST evaluate to scalar values only.
You are encouraged to use serialize/unserlialize
to store/retrieve an array in a constant:
define('CONST',serialize(array('a','b','foo'=>'bar')));
var_dump(CONST);
var_dump(unserialize(CONST));`
phpnet at trenkner dot de
14-Mar-2003 03:59
`---[Editor's Note]---
As of PHP 5.0.0 this is possible. You can define class-only constants, which can be called like Foo::Constant1 from the outside
---[End Note]---
Please keep in mind that
class AClass {
define ("Const1", "Value1");
... }
didn't work. You have to make all your constant definitions before you open the class. So
define ("Const1", "Value1");
class AClass {
... }
would be correct.`
radovan dot biciste at managestar dot com
06-Nov-2001 08:45
`Wonder how to work with variable which name is stored in a constant?
Here it is:
<?php
define("VAR_NAME","test");
// assigning value
${VAR_NAME} = "value";
// getting value back
echo ${VAR_NAME};
?>`
ste at opk dot no
29-Aug-2001 10:41
`To use a constant to show an element of an array inside a string:
define ('C', 0); print ("element 0: {$a[C]}");
The { & } around the variable signals that what's inside should be treated as a variable and not a string.
Note that 'print ("a constant:{C}");' wont work as ZERO is a constant.`
add a note
defined constant

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST