const is the simplest way to create a constant.
<?php
const APP_NAME = "Task Manager";
const MAX_ITEMS = 50;
echo APP_NAME . " allows " . MAX_ITEMS . " items.";
Task Manager allows 50 items.
Constants can hold arrays
<?php
const ROLES = ["admin", "editor", "viewer"];
echo ROLES[1];
editor
Constants can use other constants
<?php
const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60;
echo SECONDS_PER_HOUR;
3600
The value must be something PHP can work out before the script runs, so a call to a normal function (such as date()) is not allowed in a const.
const inside classes
Class constants use const too. This is where you will use it most.
<?php
class Order
{
const STATUS_PAID = "paid";
const STATUS_PENDING = "pending";
}
echo Order::STATUS_PAID;
paid
From PHP 8.3 you can add a type to a class constant, for example const string STATUS_PAID = "paid";. On older versions, that is a parse error.
Rules of const
- It must be written at the top level of the file or inside a class. It cannot sit inside an
ifor a loop. - The name is fixed when the file is compiled.
When you need a constant with a computed name or inside an if, use define() instead.
Default to const
const is the normal choice. Reach for define() only when you need to build the name or value at runtime.