PHP Constants
A constant is a named value that doesn't change. PHP has three ways to define one — pick based on where the value is known.
The three forms
| Form | When |
|---|---|
const NAME = 'value'; | Compile-time constant in the global / namespace / class scope. |
define('NAME', 'value'); | Runtime — value can be computed. |
enum Status { … } | Modern enums (8.1+) for a fixed set of named cases. |
Module-level constants
PHP
<?php const SITE_NAME = 'iwantcoding.com'; const MAX_USERS = 1000; echo SITE_NAME; // iwantcoding.com — no $ prefix
Class constants
PHP
class Status {
public const PAID = 'paid';
public const PENDING = 'pending';
public const REFUNDED = 'refunded';
}
echo Status::PAID;
Magic constants
| Constant | Returns |
|---|---|
__LINE__ | Current line number. |
__FILE__ | Full path of current file. |
__DIR__ | Directory of current file. Use this in require paths. |
__FUNCTION__ | Name of the current function. |
__CLASS__ / __METHOD__ / __NAMESPACE__ | Self-references. |
Predefined PHP constants
| Constant | Value |
|---|---|
PHP_EOL | OS line ending. |
PHP_VERSION | "8.3.0" etc. |
PHP_INT_MAX | Largest int on this platform. |
DIRECTORY_SEPARATOR | "/" or "\" — for cross-platform paths. |
Tip: Constants are case-sensitive by default — match the declared case. Use
const over define() for most cases; it's faster and works inside classes.Example
Example
<?php
const SITE = 'iwantcoding.com';
define('MAX_USERS', 1000);
echo SITE, ' ', MAX_USERS;
Try it Yourself »
Exercise
Use this keyword to declare a module-level constant.
SITE_NAME = 'iwantcoding.com';
Five letters.
Discussion
Loading…