Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Constants

Constants 11 minA constant is a named value declared with const or define that cannot be reassigned. Namespace and class rules determine how it is named and accessed.

php / Constants

Explore each scene at your own pace.

01 · The rule

The rule

Constants

A constant is a named value declared with const or define that cannot be reassigned. Namespace and class rules determine how it is named and accessed.

Choose constant names and inspect where those names can be accessed.

Pageturn charges 20% VAT on every sale, and the shop's name appears on every page. If those values live in ordinary variables, one careless $vat = 0; deep in a template can change the price of everything. Values that must never change belong in constants.

The rule

A constant is set once, has no $, and is visible everywhere.

Two ways to create one:

<?php
const VAT_RATE = 0.20;              // at the top level of a file (or in a class)
define("SHOP_NAME", "Pageturn");    // a function call; works anywhere

function withVat(float $price): float {
    return $price * (1 + VAT_RATE);  // no global needed
}

echo SHOP_NAME;           // Pageturn
echo withVat(10);         // 12

The key properties:

  • No dollar sign. You write VAT_RATE, not $VAT_RATE. By convention names are UPPER_SNAKE_CASE.
  • Set once. A second define("SHOP_NAME", ...) does not change the value; PHP issues a warning ("already defined") and keeps the original. Assigning with = is not possible at all.
  • Global visibility. Unlike variables, constants can be read inside any function without passing them in. That is safe precisely because nobody can change them.
  • Case-sensitive. VAT_RATE and vat_rate are different names.

const or define? const is checked when the file is compiled, so it must sit at the top level (or inside a class), never inside an if or a function. define() runs like any other call, so it can be used conditionally, for example after reading a configuration file. Prefer const for fixed values.

PHP also ships built-in constants you will use often: PHP_EOL (the line ending), PHP_INT_MAX (the largest integer), PHP_VERSION. And there are "magic" constants whose value depends on where they appear, such as __LINE__ (the current line number) and __DIR__ (the folder of the current file).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.