常量
在线手册:中文 英文
PHP手册

语法

可以用 define() 函数来定义常量。在 PHP 5.3.0 以后,可以使用 const 关键字在类定义的外部定义常量。一个常量一旦被定义,就不能再改变或者取消定义。

常量只能包含标量数据(booleanintegerfloatstring)。 可以定义 resource 常量,但应尽量避免,因为会造成不可预料的结果。

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

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

如果使用了一个未定义的常量,PHP 假定想要的是该常量本身的名字,如同用字符串调用它一样(CONSTANT 对应 "CONSTANT")。此时将发出一个 E_NOTICE 级的错误。参见手册中为什么 $foo[bar] 是错误的(除非事先用 define()bar 定义为一个常量)。如果只想检查是否定义了某常量,用 defined() 函数。

常量和变量有如下不同:

Example #1 定义常量

<?php
define
("CONSTANT""Hello world.");
echo 
CONSTANT// outputs "Hello world."
echo Constant// 输出 "Constant" 并发出一个提示性信息
?>

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

<?php
// 以下代码在 PHP 5.3.0 后可以正常工作
const CONSTANT 'Hello World';

echo 
CONSTANT;
?>

参见类常量


常量
在线手册:中文 英文
PHP手册
PHP手册 - N: 语法

用户评论:

0gb dot us at 0gb dot us (31-Jan-2012 01:17)

While most constants are only defined in one namespace, the case-insensitive true, false, and null constants are defined in ALL namespaces. So, this is not valid:

<?php namespace false;
const
ENT_QUOTES = 'My value';
echo
ENT_QUOTES;//Outputs as expected: 'My value'

const FALSE = 'Odd, eh?';//FATAL ERROR! ?>

Fatal error: Cannot redeclare constant 'FALSE' in /Volumes/WebServer/0gb.us/test.php on line 5

timucinbahsi at gmail dot com (11-Jan-2012 06:23)

Constant names shouldn't include operators. Otherwise php doesn't take them as part of the constant name and tries to evaluate them:

<?php
define
("SALARY-WORK",0.02); // set the proportion

$salary=SALARY-WORK*$work; // tries to subtract WORK times $work from SALARY
?>

uramihsayibok, gmail, com (09-Aug-2009 07:54)

Don't let the comparison between const (in the global context) and define() confuse you: while define() allows expressions as the value, const does not. In that sense it behaves exactly as const (in class context) does.

<?php

// this works
/**
 * Path to the root of the application
 */
define("PATH_ROOT", dirname(__FILE__));

// this does not
/**
 * Path to configuration files
 */
const PATH_CONFIG = PATH_ROOT . "/config";

// this does
/**
 * Path to configuration files - DEPRECATED, use PATH_CONFIG
 */
const PATH_CONF = PATH_CONFIG;

?>