PHP Constants

A constant is a value that never changes after it's defined. By convention constants are written in UPPER_CASE, and they have no $ prefix.

PHP
<?php
  define("SITE_NAME", "Scolar");
  const VAT_RATE = 0.13;

  echo SITE_NAME;   // Scolar
  echo VAT_RATE;    // 0.13

define() vs const

define() const
Defined at runtime compile time
Works inside if blocks yes no
Works inside classes no yes
Case-insensitive option (removed in PHP 8) no

Use const at the top level of a file and inside classes; use define() when the value has to be computed conditionally.

Constants are global

Unlike variables, constants are visible everywhere, including inside functions, with no global needed:

PHP
<?php
const TAX = 0.13;

function total(float $price): float {
    return $price * (1 + TAX); // TAX is visible here
}

Class constants

PHP
<?php
class Order {
    const STATUS_NEW = 'new';
    const STATUS_PAID = 'paid';
}

echo Order::STATUS_NEW; // new

Magic constants

PHP provides a few constants that change depending on where they're used:

PHP
<?php
  echo __LINE__;      // current line number
  echo __FILE__;      // full path of this file
  echo __DIR__;       // directory of this file
  echo __FUNCTION__;  // current function name
  echo __CLASS__;     // current class name

__DIR__ is especially useful for building reliable include paths.