PHP Constants and define()

Give fixed application values clear names with const, define(), defined() and constant().

Lesson 26 of 86Beginner8 min read

A PHP constant gives a fixed value a name. Instead of repeating the maximum number of items allowed in a basket, you can define MAX_ITEMS once and use that name wherever the rule applies. Unlike a variable, a constant has no dollar sign and cannot be reassigned during the script. That makes constants useful for stable rules, format names and configuration that has already been loaded.

This guide explains both const and define(), including when each declaration becomes available, how to check whether a name exists, and how namespaces affect access. You do not need classes yet. Start with the variables lesson, then save each complete example in its own PHP file and run it with PHP 8 or later.

Choosing a constant name and value

Names such as MAX_ITEMS, DEFAULT_LANGUAGE and APP_VERSION explain what a value means. Uppercase letters are a convention, not a language requirement. Use letters, digits and underscores, starting with a letter or underscore. Avoid names starting with two underscores because PHP uses that style for special language features. Names are case sensitive: MAX_ITEMS and max_items are different identifiers.

Choose a constant when the value must stay fixed for this execution. A user's current basket size belongs in a variable because it changes. The permitted maximum can be a constant because the rule does not change while you calculate the basket. A constant does not make a value permanently fixed across deployments; editing the application configuration changes what a later execution receives.

Scalar values and arrays are common constant values. An array constant can hold supported file extensions or named options. Its elements cannot be edited as though it were a mutable array variable. PHP has expanded the kinds of constant expressions accepted over time, so keep beginner configuration values simple and check your minimum PHP version before using newer expression forms.

const versus define()

Use const for declarations written directly in ordinary configuration or application source. Its value must be a valid constant expression. It cannot be placed inside a function or an if block as a conditional global declaration. A class can also declare constants with const, but those use class access syntax and have their own visibility rules.

Use define() when you need to establish a name at runtime, perhaps after reading an environment setting. Because it is a function call, you can put it inside a condition and pass a calculated name or value. That flexibility should serve a clear purpose. Building arbitrary constant names from request data makes code difficult to inspect and creates avoidable naming conflicts.

Neither form is a replacement for passing dependencies to functions. If many functions depend on application settings, consider passing a configuration object or array. That gives tests a straightforward way to supply different values. A handful of stable constants is readable; hundreds of globally accessible configuration names can hide which settings each function actually needs.

Availability, scope and namespaces

A global constant can be read inside a function without the global keyword. That differs from ordinary variables defined outside the function. However, the declaration must have been executed or otherwise established before you read the name. Including a configuration file too late can still cause an undefined constant error.

Namespaces add another layer. A const declaration in namespace Shop; declares Shop\MAX_ITEMS. A define() call uses the string you supply: to create that namespaced name, pass 'Shop\\MAX_ITEMS'. Use fully qualified names when clarity matters. Do not assume that placing define('MAX_ITEMS', 6) in a namespaced file automatically prefixes the string.

defined('MAX_ITEMS') checks whether a name exists. constant('MAX_ITEMS') retrieves a constant when the name is stored in a string. Prefer direct access when the name is known in source because editors can recognize it more easily. Dynamic retrieval is useful for controlled lookup tables, not for evaluating arbitrary user-supplied identifiers.

PHP Constants and define() Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Declare and read fixed values

The first declaration uses the language keyword const. The second calls a function with the constant's name as a string. Both names are read without a dollar sign. The final line reads one element from the constant array; it does not modify the array. Output appears on three lines when run in the command line.

PHP
<?php
const MAX_ITEMS = 6;
define('APP_NAME', 'Notebook Shop');
const ALLOWED_COLORS = ['blue', 'green'];

echo APP_NAME . PHP_EOL;
echo MAX_ITEMS . PHP_EOL;
echo ALLOWED_COLORS[1] . PHP_EOL;
Output
Notebook Shop
6
green

Common PHP Constants and define() Mistakes

Treating constants as variables or secret storage

Writing $MAX_ITEMS accesses a variable, not the MAX_ITEMS constant. Writing MAX_ITEMS = 8 is not legal reassignment. If your value needs to change, use a variable instead of trying to unset and recreate a constant. Also remember that a constant containing a password is still accessible application data. Keep secrets out of public source repositories and load them through a controlled configuration process.

Old tutorials sometimes use the third argument of define() to request case-insensitive constants. PHP 8 removed that behavior. Modern code should use one exact spelling. PHP 8 also throws an error for an undefined constant rather than interpreting a bare name as a string. Redeclaring an existing constant is deprecated from PHP 8.5; design bootstrap code to establish each name once. These compatibility notes are documented in the PHP constants manual.

PHP Constants and define() in Real Projects

Practical task: establish a default page size

Build a small configuration rule: if PAGE_SIZE has not been established by an earlier bootstrap file, define it as twelve. Then calculate how many pages forty-one products need. The existence check lets a caller provide a value before this file runs. It should not conceal accidental duplicate configuration files; investigate unexpected values rather than adding checks everywhere.

PHP
<?php
if (!defined('PAGE_SIZE')) {
    define('PAGE_SIZE', 12);
}

$productCount = 41;
$pageCount = (int) ceil($productCount / PAGE_SIZE);
echo 'Pages: ' . $pageCount . PHP_EOL;
Output
Pages: 4

The division produces a fractional number of pages. ceil() rounds upward because even one product on the last page requires a page. Casting makes the result an integer. Try a product count of twenty-four, then zero, and explain why the results become two and zero. A real pagination endpoint should validate any configurable page size as a positive integer before defining it.

PHP Constants and define() FAQ

Can I use a constant inside a function?

Yes. Global constants do not need global. Make sure the constant exists before the function tries to read it. The function can still become harder to test if it relies on many global configuration values.

Is const faster than define()?

Their declaration mechanisms differ, but maintainability and the required expression matter more than tiny differences in configuration startup. Choose the form that describes whether the declaration is fixed source or runtime configuration.

Can constants hold arrays?

Yes in modern PHP. Reading an item works normally. Assigning a new value to an item is not allowed because the constant value is immutable.

Should every repeated string be a constant?

No. Create a named constant when the name adds domain meaning or centralizes a rule. Replacing every display sentence with an uppercase identifier can make a small program harder to read.

PHP Constants and define() Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

A setting must be declared only after an environment value is read inside an if block. Which declaration fits?

PHP Constants and define() Quiz

2 questions to check what you learned.

  1. Which expression reads a constant named MAX_ITEMS?

    • $MAX_ITEMS
    • MAX_ITEMS
    • define(MAX_ITEMS)
  2. Which tool checks whether a named constant already exists?

    • isset('PAGE_SIZE')
    • empty(PAGE_SIZE)
    • defined('PAGE_SIZE')