The const keyword will not allow anything that may have to be "processed":
$color = "red";
const RED = "This is the color $color"; //Doesn't work
define(strtoupper($color), "This is the color $color") // Works fine
Sie können eine Konstante definieren, indem Sie entweder die define()-Funktion oder ab PHP 5.3.0 das Schlüsselwort const außerhalb einer Klassendefinition verwenden. Einmal definiert, kann eine Konstane weder verändert noch gelöscht werden.
Vor PHP 5.6 können Konstanten nur skalare Daten (boolean, integer, float und string) enthalten. Von PHP 5.6 an ist es möglich eine Konstante als skalaren Ausdruck zu definieren, und es ist ebenfalls möglich eine Array Konstante zu definieren. Es ist möglich, Konstanten vom Typ resource zu definieren, dies sollte allerdings vermieden werden, da es zu unerwarteten Ergebnissen führen kann.
Den Wert einer Konstanten erhalten Sie durch die einfache Angabe ihres Namens. Im Gegensatz zu Variablen sollten Sie einer Konstanten kein $ 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.
Hinweis: Konstanten und (globale) Variablen befinden sich in unterschiedlichen Namensräumen. Das hat zum Beispiel zur Folge, dass
TRUEund $TRUE etwas völlig Verschiedenes sind.
Falls Sie eine undefinierte Konstante verwenden, nimmt PHP an, dass Sie den Namen der Konstanten selbst meinen, so als ob Sie sie als einen string (CONSTANT vs "CONSTANT") aufgerufen hätten. Falls das passiert, wird Ihnen ein Fehler vom Typ E_NOTICE ausgegeben. Lesen Sie ebenfalls den entsprechenden Manualabschnitt, der erklärt, warum $foo[bar] falsch ist (zumindest solange Sie nicht zuvor bar mittels define() als Konstante definiert haben). Möchten Sie einfach nur nachprüfen, ob eine Konstante definiert ist, benutzen Sie die Funktion defined().
Das hier sind die Unterschiede zwischen Konstanten und Variablen:
Beispiel #1 Definiton von Konstanten
<?php
define("KONSTANTE", "Hallo Welt.");
echo KONSTANTE; // Ausgabe: "Hallo Welt."
echo Konstante; // Ausgabe: "Konstante" und eine Notice.
?>
Beispiel #2 Definition von Konstanten unter Verwendung des const-Keywords
<?php
// Funktioniert seit PHP 5.3.0
const KONSTANTE = 'Hallo Welt';
echo KONSTANTE;
// Funktioniert seit PHP 5.6.0
const ANDERE_KONSTANTE = KONSTANTE . '; Ade Welt';
echo ANDERE_KONSTANTE;
const ANIMALS = array('Hund', 'Katze', 'Maus');
echo ANIMALS[1]; // gibt "Katze" aus
// Funktioniert seit PHP 7
define('ANIMALS', array(
'Hund',
'Katze',
'Maus'
));
echo ANIMALS[1]; // gibt "Katze" aus
?>
Hinweis:
Im Gegensatz zu Konstanten, welche mit define() ersellt werden, müssen über const definierte Konstanten im Top-Level Scope erstellt werden, weil sie zur Compile Zeit definiert werden. Das heißt, dass sie nicht innerhalb von Funktionen, Schleifen, if Statements oder try/catch Blöcken definiert werden können.
Lesen Sie ebenfalls den Abschnitt über Klassenkonstanten.
The const keyword will not allow anything that may have to be "processed":
$color = "red";
const RED = "This is the color $color"; //Doesn't work
define(strtoupper($color), "This is the color $color") // Works fine
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;
?>
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
Actually, there is a way, to (re)declare FALSE (also: False, false, TRUE, NULL, etc.) constant, even if it is already declared:
<?php
var_dump(constant('I_DONT_EXIST')); // warning "Couldn't find constant I_DONT_EXIST"
var_dump(constant('FALSE')); //no warning, output: bool(false)
define('FALSE', TRUE);
var_dump(constant('FALSE')); //output: bool(true)
// but...
var_dump(constant('false')); // output: bool(false)
var_dump(FALSE); // output: bool(false);
?>
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
?>