常量

Table of Contents

常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的 魔术常量,它们其实不是常量)。常量大小写敏感。传统上常量标识符总是大写的。

Note:

在 PHP 8.0.0 之前,使用 define() 定义的常量可能不区分大小写。

常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始,后面跟着任何字母,数字或下划线。用正则表达式是这样表达的: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

还可以使用 define() 函数来定义包含保留字或非常规名称的常量,这类常量可以通过 constant() 函数来获取名称,但是非常不推荐这种用法。

Example #1 合法与非法的常量名

<?php

// 合法的常量名
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more");

// 非法的常量名
define("2FOO",    "something");

// 下面的定义是合法的,但应该避免这样做:(自定义常量不要以__开头)
// 也许将来有一天 PHP 会定义一个 __FOO__ 的魔术常量
// 这样就会与你的代码相冲突
define("__FOO__""something");

?>

Note: 在这里,字母指的是 a-z,A-Z,以及从 128 到 255(0x80-0xff)的 ASCII 字符。

superglobals 一样,常量的范围是全局的。常量可以从脚本的任何地方被访问,而不考虑作用域。有关作用域的更多信息请阅读手册中的变量范围

Note: 从 PHP 7.1.0 开始,类常量可以声明为 protected 或 private 的可见性, 使其只在其定义的类的层次范围内可用。

User Contributed Notes

mparsa1372 at gmail dot com 11-Mar-2021 05:51
<?php
//Syntax of define constant in php
//define(name, value, case-insensitive);

//it will print 100 in output
define('BOOK',100);
echo
BOOK;

//it will print 200 in output
define('book', 200 , true);
echo
book;

//results of all are the same
echo '<br>';
echo
BOOK;
echo
'<br>';
echo
book;
warwick dot jm dot barnes at gmail dot com 16-Jun-2020 07:49
The documentation says, "You can access constants anywhere in your script without regard to scope", but it's worth keeping in mind that a const declaration must appear in the source file before the place where it's used.

This doesn't work (using PHP 5.4):
<?php
foo
();
const
X = 1;
function
foo() {
    echo
"Value of X: " . X;
}
?>
Result: "Value of X: X"

But this works:
<?php
const X = 1;
foo();
function
foo() {
    echo
"Value of X: " . X;
}
?>
Result: "Value of X: 1"

This is potentially confusing because you can refer to a function that occurs later in your source file, but not a constant. Even though the const declaration is processed at compile time, it behaves a bit like it's being processed at run time.
Sumon Mahmud (Abu Taleb) 01-Feb-2020 02:21
define('MYKEY', 'The value is from outside of class');
class Abc{
   
    const MAX = 10;    

    public function __construct(){
        define('TEST', 'hello world! '); // using define function in class constructor
    }
    public function getOutput(){
        echo TEST . MYKEY . PHP_EOL; // accessing constants from outside of class
    }
}

$obj = new Abc();  // define function will call
$obj->getOutput(); // hello world! The value is from outside of class

echo Abc::MAX . PHP_EOL; // 10 - accessing constant using scope resolution

echo TEST; // hello world!  Because the constants is defined while constructor call
jcastromail at yahoo dot es 07-Oct-2017 12:13
Performance of constants.  PHP 7.1.10 32 bits (Opcache active, windows 10 i7-64bits) but apparently the trends is the same with the 5.x

using a constant declared by DEFINE('CNS',value) : 0.63575601577759s
using a constant declared by const CNS=value : 0.61372208595276s
using a variable declared by $v=value : 0.51184010505676s

In average, the use of DEFINE and CONST is around the same with some sightly  better performance of CONST instead of DEFINE. However, using a variable is around 10-50% better than to use a constant.  So, for a performance intensive task, constant is not the best option.

$p1=microtime(true);
$x=0;
for($i=0;$i<50000000;$i++) {
    $x+=CNS;
}
$p2=microtime(true);
xs2ilyas at gmail dot com 03-Feb-2017 05:38
When we start a constant name with space, it doesn't produce any error.

<?php
  define
(" YEAR"2000)
  echo
"success";
?>

output: success

But when we call this constant, it produce error.

<?php
  define
(" YEAR"2000)
  echo
YEAR;
?>

output: E_NOTICE :  type 8 -- Use of undefined constant YEAR - assumed 'YEAR' -- at line 4 YEAR
gried at NOSPAM dot nsys dot by 17-Jan-2016 07:12
Lets expand comment of 'storm' about usage of undefined constants. His claim that 'An undefined constant evaluates as true...' is wrong and right at same time. As said further in documentation ' 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...'. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant('CONST_NAME') to get constant value (BTW it also works for class constants - constant('CLASS_NAME::CONST_NAME') );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).
Raheel Khan 22-Feb-2015 08:39
class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error

<?php

class constants {

    const
MAX_VALUE = 10;
        public const
MIN_VALUE =1;

}

// This will work
echo constants::MAX_VALUE;

// This will return syntax error
echo constants::MIN_VALUE;
?>
php at webflips dot net 02-Apr-2014 08:03
It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:

<?php
define
('echo', 'My constant value');

echo
constant('echo'); // outputs 'My constant value'
?>
wbcarts at juno dot com 20-May-2012 03:04
11/14/2016 - note updated by sobak
-----

CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away.

<?php

define
('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.

class Constants
{
 
//define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

 
const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
 
const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

 
public static function getMinValue()
  {
    return
self::MIN_VALUE;
  }

  public static function
getMaxValue()
  {
    return
self::MAX_VALUE;
  }
}

?>

#Example 1:
You can access these constants DIRECTLY like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the function name exactly (with the parentheses).

<?php

#Example 1:
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE;

#Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue();

?>

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).
Andreas R. 30-Apr-2007 07:19
If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),
* DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)
* PATH_SEPARATOR (';' on Win, ':' on Linux,...)
they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in 'Directory Functions'
http://www.php.net/manual/en/ref.dir.php
hafenator2000 at yahoo dot com 21-Apr-2005 02: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 09:54
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
<?php
// Debug mode
define('DEBUG',false);
?>

test.php
<?php
include('settings.php');

if (
DEBUG) {
  
// echo some sensitive data.
}
?>

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
// Debug mode
define('DEBUG',0);
?>

test.php
<?php
include('settings.php');

if (
DEBUG == 1) {
  
// echo some sensitive data.
}
?>

Now it works correctly.
ewspencer at industrex dot com 18-Aug-2003 06:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

<?php
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:

<?php
require_once(FUNCTIONS."/database.fnc");
require_once(
FUNCTIONS."/randchar.fnc");
?>

as well as dynamic constructs, typical of value assignment to variables:

<?php
$userid 
= randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

The above convention works for me, and helps produce self-documenting code.

-- Erich
katana at katana-inc dot com 25-Feb-2002 11:53
Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有