Values that must not change
Some values in a program are fixed: the tax rate, the name of the site, the maximum number of items in a cart. You could put them in variables, but a variable can be changed by accident anywhere in the code. A constant is a name for a value that, once defined, cannot change.
<?php
const SITE_NAME = "Himanshu's Shop";
const GST_RATE = 0.18;
$price = 1000;
echo SITE_NAME . "\n";
echo "Price with GST: " . $price * (1 + GST_RATE) . "\n";Himanshu's Shop
Price with GST: 1180Notice the differences from variables: there is no $ in front of the name, and by convention constant names are written in UPPER_SNAKE_CASE so they stand out.
Constants cannot be changed
Trying to assign to a constant is not just a warning, it is a syntax error, because a constant is not a place you can store into:
<?php
const GST_RATE = 0.18;
GST_RATE = 0.12;Parse error: syntax error, unexpected token "=" in /path/to/script.php on line 3That protection is the whole point. If a value must be different on different servers, such as a database password, it belongs in a configuration file or environment variable rather than a hard-coded constant; but within one run of the program, it should not change.
const and define()
There are two ways to create a constant.
const NAME = value; is the modern, preferred form. It is read when PHP compiles the file, so it must be at the top level of a file or inside a class, not inside an if, a loop or a function.
define('NAME', value) is a function call that runs like any other statement, so it can be used conditionally:
<?php
$environment = "local";
if ($environment === "local") {
define('DEBUG', true);
} else {
define('DEBUG', false);
}
var_dump(DEBUG);
var_dump(defined('DEBUG'));
var_dump(defined('MISSING'));bool(true)
bool(true)
bool(false)defined() checks whether a constant exists without using it. Defining the same constant twice is not allowed; PHP warns and keeps the first value:
<?php
define('MAX_ITEMS', 10);
define('MAX_ITEMS', 20);
echo MAX_ITEMS . "\n";Warning: Constant MAX_ITEMS already defined in /path/to/script.php on line 3
10Constants can hold strings, numbers, booleans, null and arrays:
<?php
const SHIPPING_COUNTRIES = ['India', 'USA', 'UK'];
echo SHIPPING_COUNTRIES[1] . "\n";
echo count(SHIPPING_COUNTRIES) . "\n";USA
3Built-in constants
PHP defines many constants for you. A few that come up often:
<?php
echo PHP_MAJOR_VERSION >= 8 ? "PHP 8 or newer\n" : "Old PHP\n";
echo PHP_INT_MAX . "\n";
echo "Line one" . PHP_EOL . "Line two" . PHP_EOL;
echo M_PI . "\n";PHP 8 or newer
9223372036854775807
Line one
Line two
3.1415926535898PHP_EOL is the end-of-line character for the operating system the script runs on (\n on Linux and macOS, \r\n on Windows). It is useful when writing text files; for web pages, line endings do not matter. M_PI is printed with 14 significant digits because of PHP's precision setting; the stored value is more precise.
Magic constants
Magic constants look like constants but their value depends on where they are written. They start and end with two underscores:
<?php
echo __LINE__ . "\n";
echo basename(__FILE__) . "\n";
echo basename(__DIR__) !== "" ? "__DIR__ is set\n" : "";
function checkout(): void
{
echo "Inside " . __FUNCTION__ . "\n";
}
checkout();2
script.php
__DIR__ is set
Inside checkout__FILE__ is the full path of the current file and __DIR__ is its folder. __DIR__ is the reliable way to include another file next to the current one, as you will see in include and require. __LINE__, __FUNCTION__, __CLASS__ and __METHOD__ are mainly used in error and log messages.
Class constants
Constants that belong together are often grouped in a class, which gives them a common prefix and keeps the global namespace tidy:
<?php
class OrderStatus
{
public const PENDING = 'pending';
public const SHIPPED = 'shipped';
public const DELIVERED = 'delivered';
}
echo OrderStatus::SHIPPED . "\n";shippedYou will meet classes properly in the object-oriented section. For a fixed set of options like order statuses, PHP 8.1 enums are usually an even better choice.
Common mistakes
- Writing a $ in front of a constant.
$GST_RATEis a different, undefined variable. - Using const inside an if or a function. Use
define()when the value depends on a condition. - Putting secrets in constants in code that is shared, such as a public repository. Load them from the environment instead.
- Using an undefined constant. In PHP 8 this is an
Errorthat stops the script, not a guess as in older versions.
Exercise
Define constants for a free-shipping threshold of 500 and a flat shipping fee of 49. For cart totals of 320 and 750, print the amount to pay including shipping.
Show one possible answer
<?php
const FREE_SHIPPING_FROM = 500;
const SHIPPING_FEE = 49;
foreach ([320, 750] as $cart) {
$shipping = $cart >= FREE_SHIPPING_FROM ? 0 : SHIPPING_FEE;
echo "Cart $cart: pay " . ($cart + $shipping) . "\n";
}Cart 320: pay 369
Cart 750: pay 750Key points
- A constant holds a value that cannot change after it is defined. Its name has no $ and is written in UPPER_CASE by convention.
- const NAME = value; defines a constant at the top level or in a class. define('NAME', value) works anywhere, including inside if.
- PHP has built-in constants such as PHP_VERSION, PHP_EOL and PHP_INT_MAX.
- Magic constants such as __FILE__, __DIR__ and __LINE__ change depending on where they are used.