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. 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 add a note User Contributed Notes
sean at syoft dot com
31-Jul-2006 02: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 10: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 08: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 05: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
19-Feb-2006 04: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
08-Dec-2005 08: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 07: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
01-Dec-2005 02: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 10: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 11: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
01-Apr-2005 07: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
11-Mar-2005 03: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.
12-Feb-2005 12: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
26-Jan-2005 05: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
03-Jan-2005 09: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
23-Sep-2003 06: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
15-Mar-2003 07: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
07-Nov-2001 12: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
30-Aug-2001 01: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.