define() creates a constant, like const, but it is an ordinary function call. That means it runs while the script is running, so you can use it inside an if or give it a name that is built from a string.
<?php
define("SITE_NAME", "Code Corner");
echo SITE_NAME;
Code Corner
When define() is the right tool
<?php
$environment = "local";
if ($environment === "local") {
define("DEBUG", true);
} else {
define("DEBUG", false);
}
echo DEBUG ? "Debug is on" : "Debug is off";
Debug is on
const cannot be written inside an if, but define() can.
Check if a constant exists
Use defined() to ask, and constant() to read a constant whose name is in a string.
<?php
define("VERSION", "1.2");
var_dump(defined("VERSION"));
var_dump(defined("MISSING"));
$name = "VERSION";
echo constant($name);
bool(true)
bool(false)
1.2
const vs define()
const | define() | |
|---|---|---|
| Inside a class | Yes | No |
Inside if or loops | No | Yes |
| Name can be computed | No | Yes |
| Value can be computed with functions | No | Yes |
| Style in modern code | Preferred | Only when needed |
Defining a constant twice
PHP will not replace a constant. A second define() with the same name gives a warning, and the first value stays.
<?php
define("MODE", "first");
define("MODE", "second");
echo MODE;
Warning: Constant MODE already defined in /path/to/index.php on line 3
first
Configuration files often use define()
wp-config.php use define() for settings. Now you know what those lines mean.