PHP 7.4.0RC4 Released!

define

(PHP 4, PHP 5, PHP 7)

define名前を指定して定数を定義する

説明

define ( string $name , mixed $value [, bool $case_insensitive = false ] ) : bool

実行時に、名前を指定して定数を定義します。

パラメータ

name

定数の名前。

value

定数の値。PHP 5 では、value は スカラー値 (integerfloatstringboolean あるいは NULL) でなければいけません。PHP 7 では配列を使うこともできます。

警告

リソース型の定数を定義することもできますが、 推奨できません。予期せぬ振る舞いをする可能性があります。

case_insensitive

TRUE を指定すると、定数は大文字小文字を区別しないようになります。 デフォルトでは大文字小文字を区別します。つまり CONSTANTConstant は別の値を表すわけです。

注意:

大文字小文字を区別しないときは、定数は小文字で格納されます。

返り値

成功した場合に TRUE を、失敗した場合に FALSE を返します。

変更履歴

バージョン 説明
7.0.0 array が使えるようになりました。

例1 定数の定義

<?php
define
("CONSTANT""Hello world.");
echo 
CONSTANT// "Hello world." を出力します
echo Constant// "Constant" を出力し、警告が発生します

define("GREETING""Hello you."true);
echo 
GREETING// "Hello you." を出力します
echo Greeting// "Hello you." を出力します

// PHP 7 以降で動作します
define('ANIMALS', array(
    
'dog',
    
'cat',
    
'bird'
));
echo 
ANIMALS[1]; // "cat" を出力します

?>

参考

  • defined() - 指定した名前の定数が存在するかどうかを調べる
  • constant() - 定数の値を返す
  • 定数の節

add a note add a note

User Contributed Notes 17 notes

up
64
ravenswd at gmail dot com
4 years ago
Be aware that if "Notice"-level error reporting is turned off, then trying to use a constant as a variable will result in it being interpreted as a string, if it has not been defined.

I was working on a program which included a config file which contained:

<?php
define
('ENABLE_UPLOADS', true);
?>

Since I wanted to remove the ability for uploads, I changed the file to read:

<?php
//define('ENABLE_UPLOADS', true);
?>

However, to my surprise, the program was still allowing uploads. Digging deeper into the code, I discovered this:

<?php
if ( ENABLE_UPLOADS ):
?>

Since 'ENABLE_UPLOADS' was not defined as a constant, PHP was interpreting its use as a string constant, which of course evaluates as True.
up
28
danbettles at yahoo dot co dot uk
10 years ago
define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
up
4
me at mariusgerum dot de
1 year ago
You can define constants with variable names (works also with constant values or variables or array values or class properties and so on - as long it's a valid constant name).

<?php
   
   
# Define a constant and set a valid constant name as string value
   
define("SOME_CONSTANT", "NEW_CONSTANT");
   
   
# Define a second constant with dynamic name (the value from SOME_CONSTANT)
   
define(SOME_CONSTANT, "Some value");
   
   
# Output
   
echo SOME_CONSTANT; // prints "NEW_CONSTANT"
   
echo "<br>";
    echo
NEW_CONSTANT; // prints "Some value"
   
   
?>

Needless to say that you'll lose your IDE support for refactoring and highlighting completely for such cases.
No clue why someone would / could actually use this but i thought it's worth mentioning.
up
4
@SimoEast on Twitter
2 years ago
Not sure why the docs omit this, but when attempting to define() a constant that has already been defined, it will fail, trigger an E_NOTICE and the constant's value will remain as it was originally defined (with the new value ignored).

(Guess that's why they're called "constants".)
up
3
swisschocolate at cmail dot nu
3 years ago
I think worth mentioning is that define() appears to ignore invalid constant names.
One immediate implication of this seem to be that if you use an invalid constant name you have to use constant() to access it and obviously that you can't use the return value from define() to tell you whether the constant name used is invalid or not.

For example:
$name = '7(/!§%';
var_dump(define($name, "hello")); // outputs bool(true)
var_dump(constant($name)); // outputs string(5) "hello"
up
7
chris at peeto dot net
9 years ago
The value of a constant can be the value of another constant.

<?php

define
("NEW_GOOD_NAME_CONSTANT", "I have a value");
define("OLD_BAD_NAME_CONSTANT", NEW_GOOD_NAME_CONSTANT);

echo
NEW_GOOD_NAME_CONSTANT; // current
echo OLD_BAD_NAME_CONSTANT; // legacy

?>
up
5
eparkerii at carolina dot rr dot com
10 years ago
Found something interesting.  The following define:

<?php
define
("THIS-IS-A-TEST","This is a test");
echo
THIS-IS-A-TEST;
?>

Will return a '0'.

Whereas this:

<?php
define
("THIS_IS_A_TEST","This is a test");
echo
THIS_IS_A_TEST;
?>

Will return 'This is a test'.

This may be common knowledge but I only found out a few minutes ago.

[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores.  Hyphens do not work in defines or variables, which is expected behavior.]
up
6
Jamie
8 years ago
This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:

<?php
define
("VEG","cabbage");
require(
"another file");
define("FRUIT","apple");

// "another file":
echo VEG; // cabbage
echo FRUIT; // FRUIT
?>
up
1
axew3 at axew3 dot com
3 years ago
Php 7 - Define: "Defines a named constant at runtime. In PHP 7, array values are also accepted."

But prior PHP 7, you can maybe do this, to pass an array elsewhere using define:

$to_define_array = serialize($array);
define( "DEFINEANARRAY", $to_define_array );

... and so ...

$serialized = DEFINEANARRAY; // passing directly the defined will not work
      $our_array = unserialize($serialized);

print_r($our_array);
up
1
David Spector
2 months ago
It may be worth stating that a define function must be executed before its global constant is referenced.

Example:

Abc();
define("TEST", 23);
function Abc()
    {
    echo TEST;
    } // Abc

This code fails with a Notice-level message. TEST is treated here as being the string "TEST".
up
2
jan at webfontein dot nl
11 years ago
For translating with variables and define, take also a look on the constant() function.

Example :

<?php
define
('PAYMENT_IDEAL',"iDEAL Payment ( NL only )");
define('PAYMENT_MASTERCARD',"Mastercard Payment ( international )");

$payparam='MASTERCARD';

echo
constant("PAYMENT_$payparam");

// output :
// Mastercard Payment ( international )
?>
up
1
phen at adnerdum dot org
8 years ago
To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they're only allowed a range of 0-7:

<?php
define
('GOOD_OCTAL', 0700);
define('BAD_OCTAL', 0800);

print
GOOD_OCTAL;
print
'<br>';
print
BAD_OCTAL;
?>

Result:
448
0

---------------------------------------

Furthermore,

writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!

<?php
define
(TEST, 'Throws an E_NOTICE');
?>

Result:
Notice: Use of undefined constant TEST - assumed 'TEST'
up
0
Dale Landry
2 years ago
With php 7 you can now define arrays.

consider the following code:
<?php

define
( "EXPLENATIVES", [1 => "Foo Bar", 2 => "Fehw Bahr", 3 => "Foo Bahr", 4 => "Fooh Bar", 5 => "Fooh Bhar", 6 => "Foo Barr", 7 => "Foogh Bar", 8 => "Fehw Barr", 9 => "Fu bar", 10 => "Foo Bahr", 11 => "Phoo Bar", 12 => "Foo Bawr", 13 => "Phooh Baughr", 14 => "Foogan Bargan", 15 => "Foo Bahre", 16 => "Fu Bahar", 17 => "Fugh Bar", 18 => "Phou Baughr"]);

//set up define methods using mixed values; both array and non-array values
define("NAVBTNS", [EXPLENATIVES, "Nouns", "Verbs", "Adjectives"]);

//function to create a dropdown menu using the EXPLENATIVES array $btn=EXPLENATIVES=assoc_array

function construct_navbar_buttons(){
   
   
$btns = '<ul class="nav navbar-nav">';
                       
    foreach(
NAVBTNS as $button => $btn){
        if(
is_array($btn)){
           
$btns .= '<li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="?id='
.$btn.'">
                            <i class="glyphicon glyphicon-user"></i> You Dare Say? <i class="glyphicon glyphicon-collapse-down"></i>
                        </a>
                        <ul class="dropdown-menu dropdown-user">'
;
            foreach(
EXPLENATIVES as $key => $button){
               
$btns .= '<li><a href="#">'.$button.'</a></li>';
            }
           
$btns .= '</ul>';
        }else{   
           
$btns .= '<li><a href="#">'.$btn.'</a></li>';
        }
    }
   
   
$btns .= '</ul>';
    return
$btns;
}           

Love this new implementation!

?>
up
0
Anonymous
2 years ago
There's an undocumented side-effect of setting the third parameter to true (case-insensitive constants): these constants can actually be "redefined" as case-sensitive, unless it's all lowercase (which you shouldn't define anyway).

The fact is that case-sensitive constants are stored as is, while case-insensitive constants are stored in lowercase, internally. You're still allowed to define other constants with the same name but capitalized differently (except for all lowercase).

<?php
 
// "echo CONST" prints 1, same as "echo const", "echo CoNst", etc.
 
define('CONST', 1, true);
  echo CONST;
// Prints 1

 
define('CONST', 2);
  echo CONST;
// Prints 2
 
echo CoNsT; // Prints 1
 
echo const; // Prints 1

  // ** PHP NOTICE: Constant const already defined **
 
define('const', 3);
  echo const;
// Prints 1
 
echo CONST; // Prints 2
?>

Why would you use this?

A third party plugin might attempt to define a constant for which you already set a value. If it's fine for them to set the new value, assuming you cannot edit the plugin, you could define your constant case-insensitive. You can still access the original value, if needed, by using any capitalization other than the one the plugin uses. As a matter of fact, I can't think of another case where you would want a case-insensitive constant...
up
-1
kriscraig at php dot net
7 years ago
Some people like to have an ambiguous, engine-agnostic database include specified by assigning a single config variable to one of a series of constants.  Unfortunately, this can easily become needlessly clunky if these defines are handled in an included config.php file, since more than one hook will throw an ugly "already defined" error.

Here's a simple way to accomplish this architectural model without having to create a bunch of clumsy sanity checks that compromise scalability:

<?php

/* Available databases.  --Kris */
$dbengines = array();
$dbengines[] = "mysql";
$dbengines[] = "mysqli";
$dbengines[] = "pgsql";

foreach (
$dbengines as $engine )
{
    if ( !
defined( "_" . strtoupper( $engine ) . "_" ) )
    {
       
define( "_" . strtoupper( $engine ) . "_", $engine );
    }
}

/* Which database engine shall we use?  --Kris */
$sql_type = _MYSQLI_;

?>
Then, somewhere later in the stack....

<?php

/* Include the file with the desired sql class.  --Kris */
require_once( $sql_type . ".php" );

/* Now you can use the same code for any supported db engine.  --Kris */
$sql = new sql();
$res = $sql->query( .... );
up
-2
arsicaleksa955 at gmail dot com
2 years ago
You can also define associative array as constant:

<?php
define
("DB", [
   
"DB_HOST_NAME" => "localhost",
   
"DB_USER_NAME" => "root",
   
"DB_PASSWORD" => "password",
   
"DB_DATABASE" => "db_example"
]);

prin_r(DB);

Array ( [
DB_HOST_NAME] => localhost [DB_USER_NAME] => root [DB_PASSWORD] => password [DB_DATABASE] => db_example )
up
-1
Tomas Liubinas
1 year ago
In PHP 5 it seems it was possible to redefine predefined constants under certain circumstances. The following code will output 42 in PHP 5:

<?php
namespace NS;
define('TRUE', 42, false);
echo
TRUE;
?>

In PHP 7 the output is different (1).
To Top