文字

常量

Table of Contents

  • 语法
  • 魔术常量

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

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

Tip

请参见用户空间命名指南。

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,以及从 127 到 255(0x7f-0xff)的 ASCII 字符。

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

用户评论:

[#1] Raheel Khan [2015-02-22 20:39:54]

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

[#2] alterg79 at gmail dot com [2014-10-12 20:08:37]

There is a way to access a constant in heredoc.
Here is the example:
<?php

define("__STR",'constant.string.defined');

function heredocGetConstant($constant) {
  return constant($constant);
}

$heredocGetConstant = 'heredocGetConstant';

$my_string = <<<EOT
This is my constant printed from heredoc: {$heredocGetConstant('__STR')}
EOT;

echo $my_string;

Output:
This is my constant printed from heredoc: constant.string.defined

[#3] php at webflips dot net [2014-04-02 20:03:34]

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'
?>

[#4] wbcarts at juno dot com [2012-05-20 03:04:09]

CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, or string (no array or other object types) -- 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;         WRONG - Works INSIDE of a class definition.
//const MAX_VALUE = 1.0;         WRONG - Works INSIDE 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).

[#5] ben at bendodson dot com [2007-11-27 03:14:57]

I recently found I needed a way of retrieving the value of a constant dynamically - e.g. trying to find the value of FOO_BAR by passing 'FOO_' . $someVariableWithValueBAR.  I came up with the following solution:

<?php

define
('FOO_BAR','It works!');
define('FOO_FOO_BAR','It works again!');

// prints 'It works!'
$changing_variable 'bar';
echo 
constant('FOO_' strtoupper($changing_variable));

// prints 'It works again!'
$changing_variable 'foo_bar';
echo 
constant('FOO_' strtoupper($changing_variable));

?>


Note the use of strtoupper() as constants should be defined in uppercase for good practice - feel free to remove if you have constants defined in lowercase or you can set $changing_variable as uppercase.

Might be of some use to someone!

[#6] tudor at tudorholton dot com [2007-07-09 17:15:13]

Note that constant name must always be quoted when defined.

e.g.
define('MY_CONST','blah') - correct
define(MY_CONST,'blah') - incorrect

The following error message also indicates this fact:
Notice:  Use of undefined constant MY_CONST - assumed 'MY_CONST' in included_script.php on line 5

Note the error message gives you some incorrect information.   'MY_CONST' (with quotes) doesn't actually exist anywhere in your code.  The error _is_ that you didn't quote the constant when you defined it in the 'assumed' file.

[#7] Andreas R. [2007-04-30 07:19:39]

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

[#8] pdenny at magmic dot com [2007-02-18 09:46:26]

Note that constants can also be used as default argument values
so the following code:

<?php
  define
('TEST_CONSTANT','Works!');
  function 
testThis($var=TEST_CONSTANT) {
      echo 
"Passing constants as default values $var";
  }
  
testThis();
?>


will produce :

Passing constants as default values Works!

(I tried this in both PHP 4 and 5)

[#9] anj at aps dot anl dot gov [2005-12-20 08:42:59]

It is possible to define constants that have the same name as a built-in PHP keyword, although subsequent attempts to actually use these constants will cause a parse error. For example in PHP 5.1.1, this code

     <?php
    define
("PUBLIC""Hello, world!");
    echo PUBLIC;
    
?>


gives the error

    Parse error: syntax error, unexpected T_PUBLIC in test.php on line 3

This is a problem to be aware of when converting PHP4 applications to PHP5, since that release introduced several new keywords that used to be legal names for constants.

[#10] hafenator2000 at yahoo dot com [2005-04-21 14:09:03]

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.

[#11] storm [2005-04-18 09:54:03]

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.

[#12] kumar at farmdev [2003-10-25 17:59:40]

before embarking on creating a language system I wanted to see if there was any speed advantage to defining language strings as constants vs. variables or array items.  It is more logical to define language strings as constants but you have more flexibility using variables or arrays in your code (i.e. they can be accessed directly, concatenated, used in quotes, used in heredocs whereas constants can only be accessed directly or concatenated).

Results of the test:
declaring as $Variable is fastest
declaring with define() is second fastest
declaring as $Array['Item'] is slowest

=======================================
the test was done using PHP 4.3.2, Apache 1.3.27, and the ab (apache bench) tool.
100 requests (1 concurrent) were sent to one php file that includes 15 php files each containing 100 unique declarations of a language string.

Example of each declaration ("Variable" numbered 1 - 1500):
<?php
$GLOBALS
['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>

<?php
define
('Variable1' "A whole lot of text for this variable as if it were a language string containing a whole lot of text");
?>

<?php
$GLOBALS
['CP_Lang']['Variable1'] = "A whole lot of text for this variable as if it were a language string containing a whole lot of text";
?>


Here are the exact averages of each ab run of 100 requests (averages based on 6 runs):
variable (24.956 secs)
constant (25.426 secs)
array (28.141)

(not huge differences but good to know that using variables won't take a huge performance hit)

[#13] ewspencer at industrex dot com [2003-08-18 06:30:39]

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

[#14] katana at katana-inc dot com [2002-02-25 11:53:35]

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.

上一篇: 下一篇: