Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Constants

A constant is a name for a value that does not change while the program runs: a tax rate, a site name, the number of days in a week. Unlike a variable, a constant cannot be redefined by mistake.

Declaring

A constant is declared with the word const. There is no $ sign before the name:

<?php
 
const SITE_NAME = 'My blog';
 
echo SITE_NAME; // My blog

Constant names are written in capital letters by convention, with words separated by underscores.

A constant cannot be changed

Trying to assign a new value to a constant is an error before the program even starts. The value is computed once, at the declaration:

<?php
 
const PRICE = 200;
const TAX = PRICE * 0.2;
 
echo PRICE + TAX; // 240

A constant's value may use numbers, strings, arrays and other constants.

Why constants matter

A number with no name in the middle of the code is called "magic": it is unclear what it means. A constant gives it a name and keeps it in one place:

<?php
 
const MAX_LOGIN_ATTEMPTS = 3;
 
$attempts = 4;
 
if ($attempts > MAX_LOGIN_ATTEMPTS) {
    echo 'Too many attempts';
}

If the rule changes, only one line needs fixing.

The define function

A constant can also be created with the define() function. It works at run time, so it suits cases where the name or the value is not known in advance:

<?php
 
define('APP_MODE', 'dev');
 
echo APP_MODE;                             // dev
echo defined('APP_MODE') ? ' yes' : ' no'; // yes

The defined() function checks whether a constant exists. Prefer const in regular code.

Built-in constants

PHP has many ready-made constants:

<?php
 
echo PHP_INT_MAX, "\n"; // 9223372036854775807
echo M_PI, "\n";        // 3.1415926535898
echo PHP_EOL === "\n" || PHP_EOL === "\r\n" ? 'line break' : '';

PHP_EOL is the line break for the current system, PHP_VERSION is the PHP version.

Magic constants

Their values depend on the place in the code. They start and end with two underscores:

<?php
 
function whoAmI()
{
    return __FUNCTION__;
}
 
echo whoAmI(), "\n"; // whoAmI
echo __LINE__;       // 9

__DIR__ holds the folder of the current file — it is used to build paths to neighboring files.

Common mistake

Constants are not inserted into a double-quoted string — PHP looks only for variables there:

<?php
 
const CITY = 'London';
 
echo "City: CITY", "\n";  // City: CITY
echo 'City: ' . CITY;     // City: London

Join a constant to a string with the . operator.

Thanks for reading!

Donate to the site — we work hard for you.