Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 147 ยท Getting Started

Constants

Learn PHP constants - const versus define(), naming rules, array constants, class constants, magic constants like __LINE__ and __DIR__, and predefined ones like PHP_EOL and PHP_INT_MAX.

A constant is a name for a value that never changes while the script runs. Tax rates, the number of items per page, a version number, the path to your project folder: values like these are set once and only read afterwards. Giving them a constant name makes code easier to read (ITEMS_PER_PAGE explains itself, 20 doesn't) and guarantees nobody overwrites them by accident.

PHP has two ways to create your own constants, const and define(), plus a large set it defines for you: predefined constants such as PHP_EOL and PHP_INT_MAX, and magic constants such as __LINE__ and __DIR__, which change depending on where you use them. This lesson covers all of them.

Defining constants with const

The const keyword declares a constant. By convention, constant names are written in UPPER_SNAKE_CASE, and unlike variables they have no $:

PHP Your first constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You use a constant by writing its name. Constants are available everywhere in the script after they're defined, including inside functions, without any special keyword. That's different from variables, which are local to their function (see Variable Scope).

Constants can't change

Once defined, a constant keeps its value. There's no way to assign a new value to it; writing TAX_RATE = 0.25; isn't even valid syntax. This example fails on purpose:

PHP Assigning to a constant (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

TEXT
Parse error: syntax error, unexpected token "=" in main.php on line 5

Defining the same constant a second time is also a mistake. PHP keeps the first value and warns:

PHP Defining a constant twice (warning on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is the warning, then Bookshelf:

TEXT
Warning: Constant APP_NAME already defined, this will be an error in PHP 9 in main.php on line 4
Bookshelf

As the message says, a future PHP version will turn this into an error, so treat it as one now.

What a constant can hold

A constant can hold scalar values (int, float, string, bool), null, arrays, and enum cases. The value can be a constant expression: arithmetic, string joining and references to other constants are all allowed, as long as PHP can work out the value without running any of your functions:

PHP Constant expressions and array constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is 86400, https://example.com/api/v2, Second size: M and Number of sizes: 4. Function calls such as const NOW = time(); aren't allowed with const; that's where define() comes in.

Defining constants with define()

define() is a function that creates a constant at runtime. It takes the name as a string and the value:

PHP define() at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use defined('NAME') to check whether a constant exists (it takes the name as a string), and constant('NAME') to read a constant whose name is in a variable.

const or define()?

const define()
When it's created At compile time At runtime, when the line runs
Value Constant expressions only Any expression, including function calls
Inside if blocks or functions No (top level of a file or namespace only) Yes
Computed name No Yes
Class constants Yes (const inside a class) No
Respects namespaces Yes Only if you include the namespace in the name

Prefer const. It's clearer, it's checked when the file is compiled, it works inside classes and namespaces, and tools understand it better. Reach for define() only when the value or the decision to define it depends on something at runtime, as in configuration files that read the environment.

Case sensitivity: constant names are case-sensitive, so TAX_RATE and tax_rate are different. Old PHP versions let define() create case-insensitive constants with a third argument; that option was removed in PHP 8.0. Only true, false and null remain case-insensitive.

A preview of class constants

Constants that belong to one concept are best grouped in a class. A class constant is declared with const inside a class and read with ClassName::NAME:

PHP Class constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Class constants can have visibility (public, protected, private) and, since PHP 8.3, a declared type such as public const float FLAT_RATE = 4.95;. For a fixed set of related options, such as order statuses, enums are an even better fit. Both are covered in Class Constants and Enums.

Magic constants

Magic constants are written with two underscores on each side, and their value depends on where they appear in your code. PHP fills them in when it compiles the file:

Magic constant Value
__LINE__ The current line number
__FILE__ The full path of the current file
__DIR__ The folder containing the current file (same as dirname(__FILE__))
__FUNCTION__ The current function's name
__CLASS__ The current class's name, including its namespace
__METHOD__ The current method as Class::method
__NAMESPACE__ The current namespace
PHP Magic constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
Class: Shop\Cart
Method: Shop\Cart::addItem
Function: addItem
Line: 12
Namespace: Shop
File: main.php
Directory: /box/submission

In this editor, __FILE__ is shortened to main.php; on your own computer you'd see a full path such as /var/www/shop/src/Cart.php.

Where magic constants help

  • __DIR__ is the one you'll use most. It builds paths relative to the current file, so includes work no matter which folder the script was started from: require __DIR__ . '/config.php';. A plain require 'config.php' depends on the current working directory, a classic source of "file not found" errors.
  • __LINE__, __FUNCTION__ and __METHOD__ make debugging and log messages more precise: error_log(__METHOD__ . ': payment failed');.
  • __CLASS__ is useful inside traits and parent classes. For getting a class name as a string, modern code usually prefers ClassName::class or static::class, which you'll meet in the OOP chapter.

Predefined constants

PHP and its extensions define hundreds of constants that are always available. These are the ones you'll use most often:

PHP Useful predefined constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What they mean:

  • PHP_EOL: the line ending for the current platform ("\n" on Linux and macOS, "\r\n" on Windows). Use it for text written to terminals and files. In HTML output, line endings don't matter, and for network protocols that require "\r\n", such as HTTP headers and email, write it explicitly.
  • PHP_VERSION, PHP_MAJOR_VERSION, PHP_MINOR_VERSION: the running version, useful in diagnostics. For feature checks in code, prefer version_compare(PHP_VERSION, '8.4.0', '>=').
  • PHP_OS_FAMILY: 'Linux', 'Windows', 'Darwin' (macOS) or 'BSD'.
  • PHP_INT_MAX and PHP_INT_MIN: the largest and smallest integers, 9223372036854775807 and -9223372036854775808 on 64-bit systems. Going past them turns the result into a float, as the last line shows: float(9.223372036854776E+18). Integers and Floats explains why.
  • PHP_INT_SIZE: bytes per integer (8 on 64-bit PHP).
  • PHP_FLOAT_EPSILON: the smallest difference between 1.0 and the next float, used for comparing floats with a tolerance.
  • M_PI and other M_ math constants such as M_E and M_SQRT2.
  • DIRECTORY_SEPARATOR: / on Linux and macOS, \ on Windows. PHP on Windows accepts / in paths too, so you rarely need it.
  • E_ALL, E_WARNING and friends: error levels, used with error_reporting() (see Errors, Warnings and Notices).

You can list every constant PHP knows with get_defined_constants(true), grouped by extension. It's a long list.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line is valid PHP?

    const only accepts constant expressions, so function calls aren't allowed. define() runs at runtime and accepts any value.
  2. 2. What does this print? const LIMIT = 5; const LIMIT = 9; echo LIMIT;

    PHP keeps the first value and warns "Constant LIMIT already defined". Future versions will make this an error.
  3. 3. Why is require __DIR__ . '/config.php'; better than require 'config.php';?

    __DIR__ is the folder of the file that contains the code, so the path is right no matter where the script was started from.
  4. 4. Inside method send() of class Mailer in namespace App, what is __METHOD__?

    __METHOD__ includes the fully qualified class name and the method. __FUNCTION__ would be just send.
  5. 5. What does var_dump(PHP_INT_MAX + 1); show on 64-bit PHP?

    When integer arithmetic overflows, PHP returns a float: float(9.223372036854776E+18).

Summary

  • Constants hold values that never change. Write their names in UPPER_SNAKE_CASE, without $. They're visible everywhere after they're defined.
  • const creates constants at compile time from constant expressions (including arrays) and works in classes. define() works at runtime, accepts any value, and can be conditional. Prefer const.
  • Assigning to a constant is a parse error; defining one twice gives a warning and keeps the first value.
  • Class constants (ClassName::NAME) group related values; enums are coming later.
  • Magic constants such as __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__ and __METHOD__ depend on where they're written. Build include paths with __DIR__.
  • Predefined constants include PHP_EOL, PHP_VERSION, PHP_OS_FAMILY, PHP_INT_MAX, PHP_INT_SIZE, PHP_FLOAT_EPSILON and M_PI.

Next: Data Types, where you'll meet every type of value PHP knows and learn to read var_dump() output like a pro.