PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<Variablen ausserhalb von PHPVordefinierte Konstanten>
view the version of this page
Last updated: Sat, 19 Apr 2003

Kapitel 9. Konstanten

Eine Konstante ist ein Bezeichner (Name) f�r eine simple Variable. Wie der Name schon ausdr�ckt, kann sich der Wert einer Konstanten zur Laufzeit eines Skripts nicht �ndern (eine Ausnahme bilden die Magischen Konstanten, die aber tats�chlich keine Konstanten sind.) Eine Konstante unterscheidet zwischen Gro�- und KLeinschreinbung (case-sensitive). Nach g�ngiger Konvention werden Konstanten immer in Gro�buchstaben geschrieben.

Der Name einer Konstanten folgt den gleichen Regeln wie alle anderen Bezeichner in PHP. Ein g�ltiger Name beginnt mit einem Buchstaben oder einem Unterstrich, gefolgt von beliebig vielen Buchstaben, Nummern oder Understrichen. Als regul�rer Ausdruck geschrieben: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Anmerkung: F�r unsere Zwecke ist ein Buchstabe a-z, A-Z und die ASCII-Zeichen von 127 bis 255 (0x7f-0xff).

Der G�ltigkeitsbereich einer Konstanten ist global -- Sie k�nnen unabh�ngig vom G�ltigkeitsbereich �berall auf eine Konstante zugreifen.

Syntax

Eine Konstante k�nnen Sie �ber die Funktion define() definieren. Einmal definiert, kann eine Konstane weder ver�ndert noch gel�scht werden.

Konstanten k�nnen nur scalare Daten (boolean, integer, float und string) enthalten.

Den Wert einer Konstanten erhalten Sie ganz einfach durch die Angabe ihres Namens. Einer Konstanten sollten Sie nicht,wie bei Variablen, ein $ voranstellen. Ebenso k�nnen Sie die Funktion constant() benutzen um den Wert einer Konstanten auszulesen, wenn Sie den Namen der Konstanten dynamisch erhalten wollen. Benutzen Sie get_defined_constants() um eine Liste aller definierten Konstanten zu erhalten.

Anmerkung: Konstanten und (globale) Variablen befinden sich in unterschiedlichen Namensr�umen. Das hat zum Beispiel zur Folge, dass TRUE und $TRUE grunds�tzlich unterschiedlich sind.

Falls Sie eine undefinierte Konstante verwenden, nimmt PHP an, dass Sie den Namen der Konstanten selber meinen. Wenn das passiert wird eine Notice ausgegeben. Benutzen Sie die Funktion defined() um herauszufinden, ob eine Konstante definiert ist.

Das hier sind die Unterschiede zwischen Konstanten und Variablen:

  • Konstanten haben kein Dollarzeichen ($) vorangestellt;

  • Konstanten k�nnen nur �ber die Funktion define() definiert werden, nicht durch einfache Zuweisung;

  • Konstanten k�nnen �berall definiert werden und auf Ihren Wert k�nnen Sie ohne R�cksicht auf Namensraumregeln von Variablen zugreifen;

  • Sobald Konstanten definiert sind, k�nnen sie nicht neu definiert oder gel�scht werden; und

  • Konstanten k�nnen nur skalare Werte haben.

Beispiel 9-1. Definiton von Konstanten

<?php
define("CONSTANT", "Hallo Welt.");
echo CONSTANT; // Ausgabe: "Hallo Welt."
echo Constant; // Ausgabe: "Constant" und eine Notice.
?>



User Contributed Notes
Konstanten
add a note
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.

silvein at sonique dot com
24-Jan-2001 12: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.
yasuo_ohgaki at hotmial dot com
09-Feb-2001 02:23

"SID" is defined also. It's the same as "session_name()=session_id()" and usufull for managing session using URL.
It's mentioned in Session reference, but I thought it would appropriate mention this section, too.

"NULL" is also defined and has null type. gettype(null) returns null and is_null($val) returns true for null - PHP4.0.4pl1 or later(?)

(I would like to know ALL constants defined by PHP in one place)

I also think that the class initilizer limitation intoruduced in PHP4 should be noted here.

PHP4 does not allow;

define ('C1',1);
define ('C2',2);
class foo {
 var $val = C1 | C2;
}

Following code works.(PHP4.0.4pl1-linux)
define ('C1',1);
define ('C2',2);
class foo {
 var $val = C1;
functin foo() {
   $this->val = C1 | C2;
}
}

Details are explained

(thanks to hholzgra)

pierre dot delandsheere at rug dot ac dot be dot NOSPAM
31-Mar-2001 05:38

If you use $PHP_SELF in forms or in places where a script has to reload itself, you will get the full path relative to the web root. This is very useful because it will always work, even if you move your script around on the server. You don't need to mess around with absolute or relative paths. An example would be:

<form method=POST action=$PHP_SELF?do_something> or
<a href=$PHP_SELF?do_something>Make script do something</a>

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.

jromalo at hotmail dot com
22-Jun-2001 06:52

Constants have the same naming rules as variables (though the docs don't actually say that). So you can't begin a constant name with a number.

if you name the
constant beginning with a numeral, such as:

define ("999CONSTANT", "some value");

whereas
define ("CONSTANT999", "some value");
works fine.

carl at NOSPAM dot thep dot lu dot se
26-Aug-2001 12:10

Major difference between PHP3 and PHP4:
If you define a function that uses some constant C before you
define() C, C will be undefined in the function in PHP3 but not
in PHP4. Thus constants are more pre-processor-ish in PHP3,
but probably more useful in PHP4.

tlittle at deepdesign dot com dot au
21-Feb-2002 06:28

Also predefined (in PHP 4.1.1 on linux) are a set of LOG_* constants such as LOG_DEBUG, LOG_ERR, LOG_WARNING, LOG_INFO, LOG_CRIT.  I hit this when writing an external logging facility, and couldn't work out why some of my constants had the wrong values e.g.

<?php
define("LOG_DEBUG", 10);
print LOG_DEBUG;
?>

results in printing "7" rather than the "10" I had expected.  This cost me about 15 minutes of grief.  I would have expected some warning about trying to redefine a predefined constant.

katana at katana-inc dot com
25-Feb-2002 06: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.

alan at akbkhome dot com
23-Mar-2002 04: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);

sean at php dot net
18-Jul-2002 08:27

__FILE__ doesn't work with Zend Encoder 2.0.x (ZE does funky things with __FILE__).

This may  be fixed in the future, but we don't know when. In the mean time, Zend has suggested we use the undocumented "zend_loader_current_file()", which seems to do the same thing as __FILE__ for me.

S

fmmarzoa at gmx dot net
09-Oct-2002 05:38

Constants can be useful for i18n and l10n (internationalization and localization). I'm using a module for each language my application supports for string isolation. Each module only contains constants definitions. In example, I've this in my module 'en.php' (English):

define (strSayHello, 'Hello!');

While in my module 'es.php' (Spanish), I've the constant redefined:

define (strSayHello, '�Hola!');

The language module needed is dinamically choosen by the application based on user preferences.

All works ok, but I've had a trouble with constants that must include variable values, in example, I've something like:

define (strArticleDescr, 'Published by $article_author on $article_date in $article_lang_name');

Now, when I try to use this, the value is interpreted literally, so:

print strArticleDescr;

Will show:

Published by $article_author on $article_date in $article_lang_name

I've found a solution for this using 'eval' for parsing the constant, thats:

eval ('print "'.strArticleDescr.'";')

And now things works ok, like in example:

Published by Francisco M. Marzoa on 2002-10-09 15:39:10 in Spanish

Hope you find this useful.

gv (at) damnsw (dot) net
06-Nov-2002 03: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

hoser at yahoo dot com
12-Nov-2002 10:58

where did all the comments go?

This is really not an appropriate comment -- I hate to be a t r o l l, please delete this.

I can't edit this comment

alexatcite.gda.itesm.mx
26-Nov-2002 10:01

I got some weird behavior when initializing variables with constants.

For some reason the following code works perfectly:
$status |= STAGEONE;
$status &= EMPTY;
where both constants are integers.

But I can't seem to do this:
$status = EMPTY;

I found a way around it:
$status = constant ('EMPTY');
but I wonder why this is so...

Mike Powell
25-Mar-2003 03: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.
add a note

<Variablen ausserhalb von PHPVordefinierte Konstanten>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST