PHP: 定数 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<PHPの外部から来る変数自動的に定義される定数>
view the version of this page
Last updated: Tue, 21 Dec 2004

第 13章定数

定数は簡単な値のためのID(名前)です。この名前が示すように、定数の値 はスクリプト実行中に変更できません。(magic constantsは 例外で、これらは実際は定数ではありません。) デフォルトで定数では大文字小文字を区別します。慣習的に定数は常に大 文字で表記されます。

定数の名前は、PHPのラベルと同じ規則に従います。有効な定数の名前は、 文字またはアンダースコアで始まり、任意の数の文字、数字、アンダース コアが後に続きます。正規表現で示すと、次のようになります。 [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

例 13-1. 有効/無効な定数名の例

<?php

// 有効な定数名
define("FOO",    "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more")

// 無効な定数名
define("2FOO",    "something");

// 有効だが、避けるべき。
// PHP が、今後、自動的に定義される定数を追加すると、
// スクリプトが動作しなくなる可能性がある
define("__FOO__", "something");

?>

注意: 本節の目的においては、文字は a-z, A-Z, および127から255まで (0x7f-0xff)のASCII文字を指します。

superglobalsと同様に定数のスコープはグローバルです。 つまり、スコープによらずスクリプトの中ではどこでも定数に アクセスできます。スコープの詳細についてはマニュアルの 変数のスコープ をご覧ください。

構文

define()関数を使用することにより、定数を定義す ることが可能です。定数が一度定義されると、変更または未定義とするこ とはできません。

スカラーデータ(boolean, integer, double, string) のみが定数の中に含むこと が可能です。

単に定数の名前を指定することにより、その値を得ることが可能です。 変数とは異なり、その前に$は不要です。 定数の名前を動的に得る必要がある場合、定数の値を読むために関数 constant()を使用することも可能です。 定義済の定数の一覧を得るには、 get_defined_constants()を使用して下さい。

注意: 定数と(グローバル)変数は、異なる名前空間にあります。 例えば、TRUE$TRUE は違うものを意味します。

未定義の定数を使用した場合、ちょうどstringとして コールしたかのように(CONSTANT vs "CONSTANT")、 PHPはその定数自体の名前を使用したと仮定します。 この際、E_NOTICE が発生します。 ある定数が設定されているかどうかを知るには、 defined() 関数を使用して下さい。 なぜ $foo[bar]が間違っている (まずbarを定数としてdefine()しなければ) のかというマニュアルもご覧ください。 定数がセットされているかを単にチェックするには defined()を使用してください。

変数との違いは次のようになります。

  • 定数は、前にドル記号($)を要しません。

  • 定数を定義することができるのは、define()関数 のみです。単なる代入による定義はできません。

  • 定数は、定義することができ、変数のスコープ規則に関係なく、あら ゆる場所からアクセス可能です。

  • 定数は一度設定されると再定義または未定義とすることはできません。

  • 定数は、スカラー値としてのみ評価可能です。

例 13-2. 定数の定義

<?php
define
("CONSTANT", "Hello world.");
echo
CONSTANT; // "Hello world."を出力
echo Constant; // outputs "Constant" および通知を発生。
?>



add a note add a note User Contributed Notes
定数
Charles
12-Jan-2005 09:50
To clarify from the previous post:

When you define a constant, it becomes fixed at that point and is immutable. You can add variables - but the constant becomes the contents of that variable when the define is evaluated. If you try:

define( "_A_TEXT" , "The value is " . $arr[$i] );

It would be evaluated ONCE with the current value of the $i index of array $arr. As the post pointed out, this is probably not what you want. You can easily create:

define( "_A_TEXT" , "The value is ");
....
echo _A_TEXT . $arr[$i];

Which would give you what you wanted: the constant string with the contents of the array appended.
the_coder at colina2004 dot com
24-Jun-2004 08:42
I'm currently working on a site that has got to have two languages, and I wanted to use define's in functions to make everything simpler.

However, I ran into a problem. PHP doesn't recognize the variable in:
define("constantName", "This is an array variable - {$array[$i][2]}");

I can't use that in a for cycle, like I wanted to:

for ($i = 0; $i < count($array); $i++) {
echo constantName . "<br />"
}

The method I found (I think it's been mentioned before) is to:

define("constantName", "This is an array variable - %s");

And then:

for ($i = 0; $i < count($array); $i++) {
printf(constantName, $array[$i][2]);
}
kumar at farmdev
26-Oct-2003 12:59
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)
ewspencer at industrex dot com
18-Aug-2003 01:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

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:

require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");

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

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

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

-- Erich
php-comment-2003-july-24 at ryandesign dot de
24-Jul-2003 02:04
Late reply to fmmarzoa at gmx dot net: You're better off using sprintf format and defining your strings like this:

define('strArticleDescr', 'Published by %1$s on %2$s in %2$s');

It's more standard than what you're doing. Then instead of outputting it using an eval, do this:

echo sprintf(strArticleDescr, $article_author, $article_date, $article_lang_name');

And even better for i18n and l10n, don't use defines; use gettext. See the PHP manual section on gettext and the GNU gettext website. Gettext requires some modification of the way you think about strings but I find it worthwhile to make that adjustment.
Mike Powell
25-Mar-2003 04:46
In response to the notes above about variable references in constants, double quotes isn't a proper solution because it parses the variable at the time the constant is defined. The desired behavior is to have the variables parsed at the time the constant is referenced, and this behavior can really only be achieved by using eval(), as described above.
gv (at) damnsw (dot) net
06-Nov-2002 04:08
fmmarzoa: In PHP 4.2.2/CLI, I had no problem setting define()'s to the contents of variables:

<?
   $foo
= "PHP";
  
define( "bar", "$foo is a good thing." );
   print
bar;
?>

Will print "PHP is a good thing.".

A notable difference, however, between my example and yours is your use of single-quotes.  Strings in single quotes (') will not be expanded:

print '$foo';

Will print '$foo', not the contents of $foo.



--gv
alan at akbkhome dot com
23-Mar-2002 05:08
The __FILE__ constant in 4.2rc1 (CLI) will return the location of script specified to be run, rather than the absolute file.

eg. /usr/bin/phpmole (a softlink to /usr/lib/php/phpmole/phpmole.php)

started like this
bash#/usr/bin/phpmole
 
the line echo __FILE__ in phpmole.php will output /usr/bin/phpmole - in the CGI it would have returned /usr/lib/php/phpmole/phpmole.php

the workaround is to check for links!!
$f = __FILE__;
if (is_link($f)) $f = readlink($f);
katana at katana-inc dot com
25-Feb-2002 07:53
Warning, constants used within the heredoc syntax () 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.
afuse at yahoo dot com
11-Jun-2001 05:42
The pre-defined constant '__FILE__' does not work in same way at every version of PHP.

Some version of PHP has the relative path, and some other has the absolute path on __FILE__ constant..

Please be carefull in use..

[PS]
I have not tested at all versions of PHP but the version of 4.04pl.. and 4.05 are certainly not working in same way..  If you want to see that bug(?), I can show you an example.
silvein at sonique dot com
24-Jan-2001 01:54
It may be useful to note that, in php4 (what version this started I don't know, but it didn't do it before we upgraded to php4) __FILE__ will follow symlinks to the origional file.
tom dot harris at home dot com
05-Aug-2000 12:44
To get a full path (the equivalent of something like "__PATH__") use
dirname($SCRIPT_FILENAME)
to get the directory name of the called script and
dirname(__FILE__)
to get the directory name of the include file.

<PHPの外部から来る変数自動的に定義される定数>
 Last updated: Tue, 21 Dec 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Mon Mar 14 08:13:06 2005 Local time zone must be set--see zic manual page