A constant is like a variable that cannot be changed. You set it once, and from then on it stays the same for the whole script.
Use a constant for values that should never change: a tax rate, the name of your site, a maximum number of login attempts.
<?php
const TAX_RATE = 0.18;
$price = 1000;
$tax = $price * TAX_RATE;
echo "Tax: " . $tax;
Tax: 180
What makes constants different
- There is no
$in front of the name. - By habit, names are written in UPPER_CASE.
- A constant can be used anywhere: inside functions and classes, with no
globalkeyword. - Once set, it cannot be changed or removed.
<?php
const SITE = "Code Corner";
function welcome(): string
{
return "Welcome to " . SITE; // no global needed
}
echo welcome();
Welcome to Code Corner
What happens if you try to change one
<?php
const LIMIT = 5;
echo LIMIT;
5
Writing LIMIT = 10; later is a parse error. PHP refuses to run the file at all. Something that should not change is protected by the language itself.
Built-in constants
PHP already comes with many constants.
<?php
echo PHP_INT_MAX . PHP_EOL;
echo PHP_INT_SIZE;
9223372036854775807
8
PHP_INT_MAX is the largest whole number PHP can store on a 64-bit system, and PHP_INT_SIZE is the number of bytes an integer uses. PHP_EOL is the line ending of your operating system, so it is the safe way to end a line in command-line scripts.
The next two lessons show the two ways to create a constant: const and define().