PHP 5.6.24 is released

Konstanten

Inhaltsverzeichnis

Eine Konstante ist ein Bezeichner (Name) für einen einfachen Wert. Wie der Name bereits nahelegt, kann der Wert einer Konstanten zur Laufzeit des Skripts nicht verändert werden (ausgenommen die Magischen Konstanten, die aber keine wirklichen Konstanten sind.) Eine Konstante unterscheidet standardmäßig 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, Ziffern oder Unterstrichen. Als regulärer Ausdruck könnte das so beschrieben werden: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tipp

Siehe auch Userland Naming Guide.

Beispiel #1 Gültige und ungültige Namen für Konstanten

<?php

// Gueltige Namen fuer Konstanten
define("FOO",     "irgendwas");
define("FOO2",    "etwas anderes");
define("FOO_BAR""irgendwas ganz anderes");

// Ungueltige Namen fuer Konstanten
define("2FOO",    "irgendwas");

// Folgendes ist korrekt, sollte aber vermieden werden:
// PHP koennte eines Tages eine Magische Konstante unterstuetzen
// die Ihr Skript nicht mehr wie gewuenscht funktionieren laesst
define("__FOO__""irgendwas");

?>

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

Wie bei superglobals ist der Gültigkeitsbereich einer Konstanten global. Unabhängig vom Gültigkeitsbereich können Sie in Ihrem Skript überall auf eine Konstante zugreifen. Für mehr Information zum Gültigkeitsbereich lesen Sie bitte den Abschnitt über den Geltungsbereich von Variablen.

add a note add a note

User Contributed Notes 11 notes

up
118
wbcarts at juno dot com
4 years ago
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).
up
6
ysangkok at gmail dot com
5 months ago
Some answers notes here are outdated, const can be used outside of classes in PHP 5.3+.
up
29
storm
11 years ago
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.
up
6
Raheel Khan
1 year ago
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;
?>
up
14
katana at katana-inc dot com
14 years ago
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.
up
1
gried at NOSPAM dot nsys dot by
6 months ago
Lets expand comment of 'storm' about usage of undefined constants. His claim that 'An undefined constant evaluates as true...' is wrong and right at same time. As said further in documentation ' If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string...'. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant('CONST_NAME') to get constant value (BTW it also works for class constants - constant('CLASS_NAME::CONST_NAME') );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).
up
9
ewspencer at industrex dot com
12 years ago
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
up
1
jacob dot atam at gmail dot com
20 days ago
/*To make a constant case-insensitive add true to the third argument*/

define(name, value, case-insensitive)

eg

Define('FOO','Rasmus ',true);

echo foo;

Rasmus

By default its false.
up
2
hafenator2000 at yahoo dot com
11 years ago
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.
up
0
php at webflips dot net
2 years ago
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'
?>
up
1
Andreas R.
9 years ago
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
To Top