Question

PHP define() vs const: Differences, Usage, and Best Practices

phpconstantspsr-1psr-12

Question

In PHP, constants can be declared in two common ways:

define('FOO', 1);

or

const FOO = 1;

What are the main differences between define() and const in PHP? When should each approach be used, and why might one be preferred over the other in certain situations?

Short Answer

By the end of this page, you will understand how PHP constants work, the practical differences between define() and const, where each can be used, and which option is usually better in modern PHP code.

Concept

In PHP, a constant is a value that cannot be changed after it is defined. Constants are useful for values that should stay fixed, such as configuration flags, application names, version numbers, status labels, or mathematical values.

PHP provides two main ways to create constants:

  • define() — a function call
  • const — a language construct

Even though both create constants, they are not identical.

Core idea

The main difference is when and where the constant is defined:

  • const is part of the language syntax and is typically used when the value is known in advance.
  • define() is a function, so it runs at runtime and can be called conditionally or dynamically.

Why this matters

In real programs, this affects:

  • where you are allowed to declare constants
  • whether the constant name can be built dynamically
  • whether the constant can be declared inside conditions or loops
  • readability and code style
  • support for class constants and modern PHP practices

Important practical distinction

Use const when the constant is part of the program's structure. Use define() when you need runtime flexibility.

Common modern guidance

In most modern PHP code:

  • prefer const for normal constant declarations
  • use define() only when you need something const cannot do, such as conditional or dynamic definition

Mental Model

Think of const like a label printed into the blueprint of a building. It is part of the structure of the code itself.

Think of define() like putting a label on something while the program is already running. You can decide at runtime whether to add it and what name to give it.

So:

  • const = built into the code design
  • define() = created while the script is executing

If you already know the value and name ahead of time, const is the cleaner choice. If the program needs to decide during execution, define() gives more flexibility.

Take Quiz

Syntax and Examples

Basic syntax

Using const

const SITE_NAME = 'My App';

Using define()

define('SITE_NAME', 'My App');

Both create a constant named SITE_NAME.

Example: simple constant

<?php
const TAX_RATE = 0.2;

define('CURRENCY', 'USD');

echo TAX_RATE;   // 0.2
echo "\n";
echo CURRENCY;   // USD

Example: dynamic name with define()

<?php
$name = 'APP_MODE';
define($name, 'production');

echo APP_MODE; // production

This works because define() accepts a string for the constant name.

The equivalent with const does not work:

<?php
$name = 'APP_MODE';
const $name = 'production'; // Invalid

Example: class constant with const

<?php
class OrderStatus {
    const PENDING = 'pending';
    const PAID = 'paid';
}

echo OrderStatus::PAID;

const is the normal way to declare class constants.

Example: conditional definition with define()

<?php
if (!defined('DEBUG')) {
    define('DEBUG', true);
}

This is useful when a constant should only be created in certain situations.

Step by Step Execution

Example

<?php
$env = 'development';

if ($env === 'development') {
    define('DEBUG_MODE', true);
}

echo DEBUG_MODE;

What happens step by step

  1. $env is created and given the value 'development'.
  2. PHP checks the if condition: $env === 'development'.
  3. The condition is true.
  4. PHP executes define('DEBUG_MODE', true);.
  5. A constant named DEBUG_MODE is created at runtime.
  6. echo DEBUG_MODE; outputs 1 because true is printed as 1 in this context.

Compare with const

This would not be valid for the same purpose:

<?php
$env = 'development';

if ($env === 'development') {
    const DEBUG_MODE = true; // Invalid here
}

Why?

Because const is not meant for conditional runtime declaration like define() is.

Real World Use Cases

When const is commonly used

  • Declaring application-wide fixed values
  • Creating class constants
  • Storing enum-like values in older PHP code
  • Defining values that are known before execution starts
  • Making configuration values clearer and easier to read

Example:

const APP_NAME = 'Inventory System';
const MAX_RETRIES = 3;

When define() is commonly used

  • Defining constants only if they do not already exist
  • Creating constants based on environment or bootstrap logic
  • Building the constant name dynamically
  • Working in older codebases or legacy frameworks

Example:

if (!defined('BASE_PATH')) {
    define('BASE_PATH', __DIR__);
}

Typical app scenarios

  • Configuration bootstrap: define() may be used in startup files.
  • Class design: const is preferred for class-level fixed values.
  • Feature flags: define() can help when flags depend on runtime setup.
  • Readable domain values: const works well for status names like STATUS_ACTIVE.
Take Quiz

Real Codebase Usage

In real projects, developers usually follow a simple rule:

  • use const for constants that are part of the code design
  • use define() for bootstrapping or conditional setup

Common patterns

1. Class constants

class UserRole {
    const ADMIN = 'admin';
    const EDITOR = 'editor';
    const VIEWER = 'viewer';
}

This keeps related values grouped together.

2. Guarded bootstrap constants

if (!defined('APP_ENV')) {
    define('APP_ENV', 'production');
}

This avoids redeclaring a constant if another file already defined it.

3. Validation and branching

Constants are often used to avoid magic strings:

class PaymentStatus {
    const PENDING = 'pending';
    const SUCCESS = 'success';
    const FAILED = 'failed';
}

$status = PaymentStatus::SUCCESS;

if ($status === PaymentStatus::SUCCESS) {
    echo 'Payment completed';
}

4. Configuration markers

const API_VERSION = 'v1';

This makes it easy to update shared values in one place.

Style guidance

In modern codebases, const usually improves:

  • readability
  • static analysis
  • organization, especially inside classes
  • consistency with object-oriented PHP

define() still appears often in entry files, config bootstraps, and legacy code.

Common Mistakes

1. Using const inside conditions

Broken code:

if (!defined('DEBUG')) {
    const DEBUG = true; // Invalid
}

Use this instead:

if (!defined('DEBUG')) {
    define('DEBUG', true);
}

2. Trying to create dynamic constant names with const

Broken code:

$name = 'VERSION';
const $name = '1.0'; // Invalid

Use this instead:

$name = 'VERSION';
define($name, '1.0');

3. Forgetting that constants cannot be changed

Broken code:

const LIMIT = 10;
LIMIT = 20; // Invalid

A constant is meant to stay fixed after definition.

4. Using global constants when a class constant is better

Less clear:

const STATUS_PAID = 'paid';
const STATUS_PENDING = 'pending';

Often better:

class OrderStatus {
    const PAID = 'paid';
    const PENDING = 'pending';
}

This groups related values logically.

5. Redefining a constant accidentally

Broken code:

define('APP_NAME', 'Store');
define('APP_NAME', 'Shop');

Avoid this by checking first:

if (!defined('APP_NAME')) {
    define('APP_NAME', 'Store');
}

Comparisons

define() vs const

Featureconstdefine()
TypeLanguage constructFunction
When evaluatedAs part of code structureAt runtime
Dynamic constant nameNoYes
Conditional declarationNoYes
Works for class constantsYesNo
Common in modern PHPYesSometimes
Best forFixed, known constantsRuntime or conditional constants

Which one should you choose?

SituationBetter choice
A fixed value known in advanceconst
A class-level constantconst
A constant created only if neededdefine()
A constant name built from a variabledefine()
Modern application codeUsually const
Legacy bootstrap/config fileOften define()

Related comparison: class constant vs regular constant

TypeExampleScope
Global constantconst APP_NAME = 'My App';Available globally after declaration
Class constantclass App { const VERSION = '1.0'; }Accessed through the class
Take Quiz

Cheat Sheet

Quick rules

  • Use const for most fixed constants in modern PHP.
  • Use define() when you need runtime flexibility.
  • Use const for class constants.
  • Use define() if the constant name comes from a variable.
  • Use define() inside conditional logic.

Syntax

const NAME = 'value';
define('NAME', 'value');

Best-fit guide

  • Known ahead of time: const
  • Inside a class: const
  • Conditional setup: define()
  • Dynamic naming: define()

Checks

defined('NAME');

Example patterns

const VERSION = '1.0';
if (!defined('DEBUG')) {
    define('DEBUG', true);
}

Edge cases

  • const cannot use a variable as the constant name.
  • const is not for conditional runtime declaration.
  • define() cannot declare class constants.
  • Constants cannot be reassigned after definition.

FAQ

Is const better than define() in PHP?

Usually yes for normal constant declarations, because it is cleaner and fits modern PHP style. But define() is still useful when the constant must be created dynamically or conditionally.

Can define() be used inside an if statement?

Yes. That is one of its key advantages.

Can const be used inside a class?

Yes. In fact, const is the standard way to declare class constants.

Can I create a constant name from a variable with const?

No. For that, use define().

Are constants global in PHP?

A regular constant declared with const or define() is globally accessible after it is declared. Class constants belong to the class and are accessed with ClassName::CONSTANT_NAME.

Can a PHP constant be changed later?

No. Once a constant is defined, its value cannot be changed.

Why do many older PHP projects use define() a lot?

Older codebases often used procedural bootstrap files where runtime configuration and conditional declaration were common.

Should I use constants for every fixed value?

Not always. Use constants for values that are reused, important to meaning, or should never change. Avoid creating constants for trivial one-time literals.

Take Quiz

Mini Project

Description

Create a small PHP configuration script for an application startup process. This project demonstrates when to use const for fixed application metadata and when to use define() for values that may depend on runtime setup.

Goal

Build a script that declares fixed app information with const and conditionally defines environment-based settings with define().

Requirements

  1. Declare at least two fixed constants using const.
  2. Conditionally define a DEBUG constant using define().
  3. Output all constant values.
  4. Include one class that uses const for related status values.
Take Quiz

Keep learning

Related questions

View more