PHP ยท Chapter 11 of 44

PHP Constants

A constant is an identifier for a value that cannot change during script execution. PHP constants are defined using the define() function or, since PHP 7, with the const keyword outside of functions.

Unlike variables, constants do not use a $ sign before their name, and by convention are usually written in uppercase letters to distinguish them from regular variables.

Syntax
define("NAME", value);
const NAME = value;

Defining constants

define("NAME", value) creates a constant at runtime, while const NAME = value; is used at the top level or inside classes and is resolved at compile time.

Using constants

Once defined, a constant is accessed simply by its name, without a $ sign, and it is available globally throughout the script.

Example 1 (php)
<?php
  define("GREETING", "Hello!");
  echo GREETING;
?>
Output
Hello!

define() creates a constant that is used later without a $ sign.

Example 2 (php)
<?php
  const SITE_NAME = "MySite";
  echo SITE_NAME;
?>
Output
MySite

const declares a constant directly, commonly used at the top of a script or in a class.

Key points

  • Constants are defined with define() or const.
  • Constant names do not use a $ prefix.
  • By convention, constant names are written in uppercase.
  • Once set, a constant's value cannot change during execution.
๐Ÿ’ก Note: Use constants for values that should never change, such as configuration settings or fixed limits.

๐Ÿ“ Quick Quiz

1. Which function defines a constant at runtime?

2. Do constants use a $ sign?

3. What is the naming convention for PHP constants?