Constants

Constants with const/define and how to organize configuration safely.

On this page

What Constants Are

Constants are values that do not change once defined. They are useful for configuration, fixed strings, and system-wide settings. Avoid using constants for secrets (API keys) in source control—use environment variables instead.

Define Constants with const

const is resolved at compile time and is commonly used in classes and config files.

<?php
const APP_NAME = 'Modern Dev Handbook';
const ITEMS_PER_PAGE = 20;

Define Constants with define()

define() is evaluated at runtime. It is sometimes used for conditional constants.

<?php
define('APP_ENV', 'local');

Constants in Classes

Class constants are a clean way to group related fixed values.

<?php
class UserRole {
  public const ADMIN = 'admin';
  public const EDITOR = 'editor';
}

Practical Config Pattern

A simple approach is to keep non-secret configuration in a config file and environment-specific values in environment variables.

<?php
// config/app.php
const ITEMS_PER_PAGE = 20;