Skip to main content

PHP Constants

A constant holds a value much as a variable does, with one key difference: after you define it, you can neither change it nor undefine it.

PHP gives you two ways to create one, the define() function and the const keyword.

Names follow a simple rule: begin with a letter or an underscore, and leave out the $ sign that variables use.


PHP define() Function

define() creates its constant at run-time.

The constant always lands in the global scope, even when define() is called inside a conditional block (if/else, loops, functions). Class constants, however, are out of reach for this function.

It takes two parameters:

  • CONSTANT_NAME - what the constant is called (case-sensitive)
  • value - what the constant holds

Create a constant with define()

Here define() creates a constant called "GREETING", and echo prints it. Note the missing $ sign:

Prompt
Write a PHP script that creates a constant named "GREETING" with the value "Welcome to PromptCookbook!" using define(), then echoes the constant.
Output: PHP script

Constant inside a function

The constant is created inside myTest(), yet the code outside the function can still print it:

Prompt
Write a PHP script that declares a constant inside a function using define(), calls the function, then outputs the constant outside the function.
Output: PHP script

define() syntax

This is the general form of a define() call:

index.php
<?php
define(CONSTANT_NAME, value);
?>

PHP const Keyword

With const, the constant is created at compile-time instead.

That timing is why it has to sit at the top-level scope. You can't use const this way inside functions, loops, if/else statements or try/catch blocks.

Unlike define(), it also works for class constants.

Names are case-sensitive here as well.

Create a constant with const

The same "GREETING" constant, this time made with const:

Prompt
Write a PHP script that creates a constant named "GREETING" using the const keyword and echoes it.
Output: PHP script

const syntax

This is the general form of a const declaration:

index.php
<?php
const CONSTANT_NAME = value;
?>

PHP Array Constants

A constant doesn't have to hold a single value. Both define() and const accept arrays too.

Create array constants

One array constant comes from each approach, and elements are read by index as in any array:

Prompt
Write a PHP script that creates array constants using both define() and const, then accesses elements from each.
Output: PHP script