CakeFest 2024: The Official CakePHP Conference

语法

可以使用 const 关键字或 define() 函数两种方法来定义一个常量。函数 define() 允许将常量定义为一个表达式,而 const 关键字有一些限制,具体可参见下述章节。一个常量一旦被定义,就不能再改变或者取消定义。

使用 const 关键字定义常量时,只能包含标量数据(boolintfloatstring)。可以将常量定义为一个表达式,也可以定义为一个 array。还可以定义 resource 为常量,但应尽量避免,因为可能会造成不可预料的结果。

可以简单的通过指定其名字来取得常量的值,与变量不同,不应该在常量前面加上 $ 符号。如果常量名是动态的,也可以用函数 constant() 来获取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。

注意: 常量和(全局)变量在不同的名字空间中。这意味着例如 true$TRUE 是不同的。

如果使用了一个未定义的常量,则会抛出 Error。 在 PHP 8.0.0 之前,调用未定义的常量会被解释为一个该常量的 字符串,即(CONSTANT 对应 "CONSTANT" )。 此方法已在 PHP 7.2.0 中被废弃,会抛出一个 E_WARNING 级错误。(PHP 7.2.0 之前会发出一个 E_NOTICE 级的错误。)参见手册中为什么 $foo[bar] 是错误的(除非 bar 是一个常量)。这不适用于 (完全)限定的常量,如果未定义,将始终引发 Error

注意: 如果要检查是否定义了某常量,请使用 defined() 函数。

常量和变量有如下不同:

  • 常量前面没有美元符号($);
  • 常量可以不用理会变量的作用域而在任何地方定义和访问;
  • 常量一旦定义就不能被重新定义或者取消定义;
  • 常量只能计算标量值或数组。

示例 #1 定义常量

<?php
define
("CONSTANT", "Hello world.");
echo
CONSTANT; // 输出 "Hello world."
echo Constant; // 抛出错误:未定义的常量 "Constant"
// 在 PHP 8.0.0 之前,输出 "Constant" 并发出一个提示级别错误信息
?>

示例 #2 使用关键字 const 定义常量

<?php
// 简单的标量值
const CONSTANT = 'Hello World';

echo
CONSTANT;

// 标量表达式
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo
ANOTHER_CONST;

const
ANIMALS = array('dog', 'cat', 'bird');
echo
ANIMALS[1]; // 将输出 "cat"

// 常量数组
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo
ANIMALS[1]; // 将输出 "cat"
?>

?>

注意:

和使用 define() 来定义常量相反的是,使用 const 关键字定义常量必须处于最顶端的作用域,因为用此方法是在编译时定义的。这就意味着不能在函数内,循环内以及 iftry/catch 语句之内用 const 来定义常量。

参见

add a note

User Contributed Notes 2 notes

up
32
souzanicolas87 at gmail dot com
2 years ago
the documentation doesn't go too far in explaining the crucial difference between the two ways of declaring constants in PHP.

Const is handled at compile time, define() at run time. For this reason, a constant cannot be conditionally defined using Const, for example.

Another difference we can notice occurs in the constant declarations in classes. Const infiltrates the class scope, while define() leaks into the global scope.

<?php

Class Myclass (){
const
NAME = "Nicolas";
}

?>

The NAME constant is within the scope of the MyClass class.
up
8
login at (two)view dot de
6 years ago
Just a quick note:
From PHP7 on you can even define a multidimensional Array as Constant:

define('QUARTLIST',array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul'));

does work as expected.
To Top