iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FormWhen
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

ConstantReturns
__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

ConstantValue
PHP_EOLOS line ending.
PHP_VERSION"8.3.0" etc.
PHP_INT_MAXLargest 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';

Test yourself

Q1. Best way to declare a class-level constant…
Q2. __DIR__ holds…
Q3. PHP_EOL is…

Discussion

Loading…