©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
(PHP 4, PHP 5)
define — 定义一个常量
$name
, mixed $value
[, bool $case_insensitive
= false
] )在运行时定义一个常量。
name
常量名。
value
常量的值;仅允许标量和 null 。标量的类型是 integer , float , string 或者 boolean 。 也能够定义常量值的类型为 resource ,但并不推荐这么做,可能会导致未知状况的发生。
case_insensitive
如果设置为 TRUE
,该常量则大小写不敏感。默认是大小写敏感的。比如,
CONSTANT 和 Constant 代表了不同的值。
Note:
大小写不敏感的常量以小写的方式储存。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
Example #1 定义常量
<?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."
?>
[#1] fernandopsilveira at yahoo dot com dot br [2015-09-23 17:05:34]
Just like define(), defined() will check for constants exactly as specified. So, if you want to check a constant in a namespace, you will need to specify the namespace in your call to defined(), even if you're calling defined() from within a namespace.
To check for a defined constant within current namespace, you can use __NAMESPACE__ magic variable:
<?php
namespace mytest;
define('mytest\CONSTANTINE', 'value');
if (defined(__NAMESPACE__ . '\CONSTANTINE')) {
print "Constant is defined and is valued " . CONSTANTINE;
}
?>
[#2] ravenswd at gmail dot com [2015-02-22 03:11:45]
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.
[#3] daevid at daevid dot com [2014-02-19 17:45:50]
Be aware that undefined constants are not evaluated the same as undefined variables (which is frustratingly counter-intuitive)...
$ php -a
php > if (!DO_IT) echo "don't do it\n"; else echo "do it\n";
do it
php > var_dump(DO_IT);
string(5) "DO_IT"
php > if (!$DO_IT) echo "don't do it\n"; else echo "do it\n";
don't do it
php > var_dump($DO_IT);
NULL
You have to specifically check for the definition like so...
php > if(!defined('DO_IT') || (defined('DO_IT') && !DO_IT))echo "don't do it\n"; else echo "do it\n";
don't do it
*sigh*
[#4] php at richardneilll dot org [2013-07-14 00:15:34]
In PHP, define does not have the same gotchas as the C-preprocessor. E.g.
//In PHP:
define ("x", 5+2); //x is evaluated as 7
echo 3 * x; //This is 21, as you'd expect.
//But in C:
#define x 5+2; //x is the string "5+2", substituted later.
printf ("%d", 3*x); //This is 17.
[#5] New Social Life [2012-08-17 14:59:41]
I want to show you how to define multiple things at once
just use this small function: ( i'm trying to do it even smaller... but i think is small enough )
<?php function ??define($a){foreach($a as $k => $v)define($k, $v);} ?>
usage example:
<?php
??define(array(
"second" => 1,
"minute" => 60,
"hour" => 3600,
"day" => 86400,
"week" => 604800,
"month" => 2592000, // 30 days month
"year" => 31536000,
"year2" => 31622400
));
?>
PLEASE NOTE:
there AREN'T three points, there is the three points CHARACTER, to be sure, just copy paste my code
[#6] kriscraig at php dot net [2012-03-23 21:47:17]
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
$dbengines = array();
$dbengines[] = "mysql";
$dbengines[] = "mysqli";
$dbengines[] = "pgsql";
foreach ( $dbengines as $engine )
{
if ( !defined( "_" . strtoupper( $engine ) . "_" ) )
{
define( "_" . strtoupper( $engine ) . "_", $engine );
}
}
$sql_type = _MYSQLI_;
?>
Then, somewhere later in the stack....
<?php
require_once( $sql_type . ".php" );
$sql = new sql();
$res = $sql->query( .... );
[#7] phen at adnerdum dot org [2011-07-06 01:32:03]
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:
<?
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'
[#8] kobrasrealm at gmail dot com [2011-06-10 18:31:46]
When going back to rewrite code, it might be tempting to have a constant &reference a variable, but it doesn't work.
<?php
header("Content-type: text/plain");
$variable = "value";
define("MYCONSTANT", &$variable);
echo $variable."\n";
echo MYCONSTANT."\n";
echo "------\n";
$variable = "different";
echo $variable."\n";
echo MYCONSTANT;
?>
Produces this:
value
value
------
different
value
I doubt it's supposed to work, either. :)
[#9] Jamie [2011-03-01 13:24:13]
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
?>
[#10] andreas at cap-systems dot com [2011-02-05 04:54:07]
Constant name must not written as string. The following code works also:
<?php
define(MY_NAME, 'value');
define('ANOTHER_NAME', 'value2');
if(defined('MY_NAME')) {
echo MY_NAME . '<br />';
}
if(defined('ANOTHER_NAME')) {
echo ANOTHER_NAME . '<br />';
}
echo MY_NAME . '<br />';
echo ANOTHER_NAME . '<br />';
?>
Output:
value
value2
value
value2
Tested with:
- PHP 5.3.1 on XAMPP on Windows Vista (local)
- PHP 5.2.42 on Apache 2.0 on Linux (remote)
- PHP 5.2.12 on Apache 2.0 on Linux (remote)
[#11] angelos at unkreativ dot org [2011-01-09 01:18:56]
Something I found out the "hard" way today: integers starting with 0 won't work.
<?
define('SOMECONSTANT', 09900);
var_dump(SOMECONSTANT);
?>
Produces int(0)
<?php
define('SOMECONSTANT', 9900);
var_dump(SOMECONSTANT);
?>
Produces int(9900)
[#12] toph at farmer corp dot c om [2010-10-16 02:51:15]
Hi,
Here is a trick to use constants within the heredoc notation.
<?php
define('MY_CONSTANT','foo bar')
$cst = 'cst';
function cst($constant){
return $constant;
}
$string = <<<EOF
My constante MY_CONSTANT : {$cst(MY_CONSTANT)} ...
EOF;
echo $string;
?>
That will echo :
My constante MY_CONSTANT : foo bar ...
As you can use function within the heredoc notation the idea is to use a fonction to return the value of the constant.
Be carefull, to use a function, it's necessary to declare the name of the function as a variable and to use that varaible during the "call" of the constant.
It works for me and doesn't seem too messy.
Hope that will help.
[#13] rush at bigup dot com dot pa [2010-08-10 10:23:09]
Just in case:
You cannot set a constant to be a class. For example:
define ("WSDLCLIENT",new soapclient(WSDLSERVER, 'wsdl'));
You cannot do this.
[#14] chris at peeto dot net [2010-03-25 19:15:19]
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
?>
[#15] bohwaz.net [2009-08-15 17:54:50]
Note that define don't care at all about the constant name, you can give everything as a constant name, even if the PHP documentation says that the allowed characters are [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Just try this :
<?php define('anything::()$', 'test'); ?>
You won't be able to access this constant though, it will throw a parse error, either through constant() or define(), but if you do that :
<?php print_r(get_defined_constants()); ?>
You will see that the constant is registered at the end of the array. Yes that's totally useless. But you can try other things that will work with constant() :
<?php define('...', 'test'); echo constant('...'); ?>
Will echo 'test'. Yeah that's a pretty strange behavior.
And please note that defining object constants outside of objets don't work :
<?php
class myObject { }
define('myObject::CONSTANT', 'test');
?>
[#16] Anonymous [2009-07-19 22:31:00]
My notice to: redeclare define - it is possible
php -v
--> PHP 5.2.6-3ubuntu4.1 with Suhosin-Patch 0.9.6.2
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
php -r "define('TEST','foo',true);
var_dump(TEST);
define('TEST','bar');
var_dump(TEST);"
string(3) "foo"
string(3) "bar"
greetings
[#17] sixd at php dot net [2009-07-17 14:24:22]
A note on redefining:
Constants can't be redefined:
$ php -r "define('A', 1); var_dump('A'); define('A', 2); var_dump('A');";
string(1) "A"
PHP Notice: Constant A already defined in Command line code on line 1
string(1) "A"
But using the case insensitive setting shows that the internal
representation is lower case:
$ php -r "define('A', 1, true); var_dump('A'); define('A', 2); var_dump('A');";
string(1) "A"
string(1) "A"
Note the lower case 'a' in the second define() here:
$ php -r "define('A', 1, true); var_dump('A'); define('a', 2); var_dump('A');";
string(1) "A"
PHP Notice: Constant a already defined in Command line code on line 1
string(1) "A"
[#18] danbettles at yahoo dot co dot uk [2009-04-14 11:56:37]
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!');
?>
[#19] Aldonio [2009-03-27 08:24:33]
This code will define every key of an array, and if its a multidimentional array it will define it as parent_child1_child2_etc.
<?php
function define_array( $array, $keys = NULL )
{
foreach( $array as $key => $value )
{
$keyname = ($keys ? $keys . "_" : "") . $key;
if( is_array( $array[$key] ) )
define_array( $array[$key], $keyname );
else
define( $keyname, $value );
}
}
?>
[#20] ceo at l-i-e dot com [2009-03-11 14:04:30]
In PHP 4.4.9, you cannot use certain names for constants.
Specifically, reserved words such as 'PRINT', 'IF', etc.
Oddly enough, you get different behaviour for some:
<?php
define('IF', 42);
echo "IF: ", IF, "<hr />\n";
?>
yields PHP Parse error: syntax error, unexpected T_IF
<?php
define('PRINT', 13);
echo "PRINT: ", PRINT, "<hr />\n";
?>
yields PHP Parse error: syntax error, unexpected ')'
Not sure if this is still true in PHP 5 or not, but it's worth noting if it is.
[#21] Anonymous [2009-03-09 13:03:47]
With php 5.30 it is possible to make some "restrictions", in case u use namespaces...
The following function allows only uppercase and, if 3 param isset, gives E_USER_ERROR instead of E_NOTICE:
<?php
namespace bla;
function define($c,$v,$x=false) {
$c = strtoupper($c);
if (!defined($c)) {
// not to use \define here, as the syntax highlighting does not work correctly here...
return define($c, $v, true);
} else if ($x == true) {
trigger_error('setting constant "'.$c.'" is not allowed', E_USER_ERROR);
}
return null;
}
define('PHP_VERSION', '1');
define('PHP_VERSION', '1') || trigger_error('constant already defined', E_USER_NOTICE);
define('PHP_VERSION', '1', true);
?>
[#22] jv at vip dot ie [2009-03-08 16:14:36]
Probably the most efficient way of creating a constant array is to put it in a function like this:
<?php
function my_const_arr()
{
return array
(
'key1' => 'val 1',
'key2' => 'va' 2'
);
}
?>
Then use at will like so...
<?php $my_const_arr = my_const_arr(); ?>
[#23] usuroer dot king at hotmail dot co dot uk [2009-03-08 04:15:40]
Referring to "This-Is-A-Test" constant below.
When echoing it the script thinks you performing a series of minus (subtraction) thus since THIS and IS, A, TEST are not defined they are 0 by default. So 0-0-0-0 = 0.
As explained that a hyphen cannot be used within a variable.
[#24] downwind at web dot de [2009-02-01 20:48:25]
I'm reffering to the note below by mittiprovence.
The described behavior has nothing to do with the fact that there is a constant in the condition.
Comparing a non-numeric string to the integer 0 by using == will return true, since the string will be casted to integer - which will be zero. If your string starts with a number, it will be castet to an integer with the number as value.
To avoid the described behavior, you should use === instead of ==.
Finally, the behavior discribed by mittiprovence is exacly the expected behavior as defined in the manual.
For further information read the manual:
http://www.php.net/manual/en/types.comparisons.php
http://www.php.net/manual/en/language.operators.comparison.php
http://www.php.net/manual/en/language.types.string.php #language.types.string.conversion
<?php
if (0 == "some string") { // is true
echo "0 == 'some string'";
}
if (1 == "some string") { // is false
echo "1 == 'some string'";
}
if (1 == "1 some string") { // is true
echo "1 == '1 some string'";
}
if (0 === "some string") { // is false
echo "0 === 'some string'";
}
?>
[#25] eparkerii at carolina dot rr dot com [2008-10-22 12:01:16]
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.]
[#26] jan at webfontein dot nl [2008-07-27 05:20:05]
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 )
?>
[#27] thscheer at web dot de [2008-06-20 02:18:09]
How to define an array as constant with define?
there is a simple way to define an array of values as constant...
just
define ("constant-name","value1,value2,value3,value4");
$t_array = preg_split('/,/', constant(constant-name), -1, PREG_SPLIT_NO_EMPTY);
var_dump($t_array);
array(4) { [0]=> string(6) "value1" [1]=> string(6) "value2" [2]=> string(6) "value3" [3]=> string(6) "value4" }
Now you can iterate over the array defined as constant ...
[#28] ceo at l-i-e dot com [2008-05-05 08:30:56]
I'm not sure if it's version dependent, but apparently this works:
define('APPLICATION_NOW', time());
This can be quite handy for time-dependent code...
You can then do:
class foo {
$private now = APPLICATION_NOW;
}
and have a consistent time-stamp across the application, which is nice.
Works for me in 5.2.5
I didn't think it worked before...
[#29] jason@sitehatchery dot com [2008-04-24 23:28:06]
You can store your constant as the value of a variable like this:
$variable=VARIABLE;
To access the constant, do this: constant($variable).
Beware: if your variable changes, then you loose your reference to the constant - but the constant itself will not change.
I've found this especially useful for storing the constant string (i.e. VARIABLE) in a database.
[#30] rayro at gmx dot de [2007-09-15 14:53:00]
just a note to the previous post by e s lin d sey at g mail dot co m:
Well as u said, it is not the best workaround. To resolve this "Problem" without getting incredible loss of performance, you are able to make the use of "variable functions" like "variable variables":
<?php
$def = 'constant';
$string = <<<END
This is PHP running on<br />
{$def('PHP_OS')}
END;
var_dump($string);
?>
In this example we make use of the "constant" function which is builtin, and it will output:
string(37) " This is PHP running on
WINNT"
Tested on PHP 5...
Best regards
[#31] e s lin d sey at g mail dot co m [2007-08-13 13:38:40]
Constants can't be referenced from within quotes or (more importantly IMHO) from within HEREDOC syntax. This is a huge drawback in my opinion. Here's two of my workarounds:
<?php
//PHP5 only -- more efficient
$constarray = get_defined_constants(true);
foreach($constarray['user'] as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));
//PHP4+ -- less efficient because it defines (potentially) hundreds of unnecessary constants
foreach(get_defined_constants() as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key), addslashes($val)));
?>
Now you can refer to your defined constants using the $_CONSTANTS array. Note that because this is NOT a superglobal, a few caveats apply:
<?php
//run code snippet here to define $_CONSTANTS in global scope...
$mv = $_CONSTANTS['FOO']; //works
function my_function1()
{
$mv = $_CONSTANTS['BAR']; //doesn't work! not defined!
}
function my_function2()
{
global $_CONSTANTS;
$mv = $_CONSTANTS['BAR']; //ah, this works!
}
?>
I realize this is not ideal, either for performance or for convenience of being able to refer to constants without regard to scope, but it is a workaround that works. Depending on your application, it may be easier to shift your paradigm a bit and use the following method instead, declaring your constants as variables first:
<?php
//first, define our constants...
$_CONSTANTS['FOO'] = 'bar';
$_CONSTANTS['BAR'] = 'foo';
//now, turn them into real constants...
foreach($_CONSTANTS as $key => $val)
define($key, $val);
//now, you can use either format to refer to a constant
print($_CONSTANTS['FOO']); //prints 'bar'
print(FOO); //prints 'bar'
print("$_CONSTANTS['FOO']"); //prints 'bar'
//prints 'blah bar blah'
print <<<EOF
blah {$_CONSTANTS['FOO']} blah
EOF;
?>
Hope this helps some of you out there, I know being able to utilize my constants in HEREDOC helped me a ton!
[#32] smifffy at smith-net dot org dot uk [2007-07-25 16:23:01]
a basic function to auto assign a numeric value that increase by itself each time - used in some permission style scripts
<?php
function define_bitwise($constant_name, $reset = False)
{
static $bitwise_next = 1;
if ( $reset === True )
{
$bitwise_next = 1;
}
define($constant_name, $bitwise_next);
$bitwise_next += $bitwise_next;
}
?>
when reset it set to True, resets that value to 1 and starts afresh
[#33] creeves at dja dot com [2007-07-19 06:59:50]
Intersting to note:
I found this in php5 on windows
If you try to unset a constant (which you cant but maybe you have a Jr. programmer or something). The error message that is thrown is:
<?php
define ("SOME_CONSTANT", true);
unset (SOME_CONSTANT);
?>
Parse error: parse error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM
[#34] nl-x at bita dot nl [2007-07-09 10:34:49]
Watch out. You can define a new constant with the name NULL with define("NULL","FOO");. But you must use the function constant("NULL"); to get it's value. NULL without the function call to the constant() function will still retrieve the special type NULL value.
Within a class there is no problem, as const NULL="Foo"; will be accessible as myClass::NULL.
[#35] stangelanda at arrowquick dot com [2006-12-31 18:59:07]
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
?>
[#36] [2005-02-11 20:45:59]
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
[#37] phpnet at trenkner dot de [2003-03-14 15:59:47]
---[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.
[#38] radovan dot biciste at managestar dot com [2001-11-06 20:45:38]
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};
?>