Skip to main content

PHP Constants

By SamK
0
0 recommends
Category(s)
Topic(s)

Constants are similar to variables, but once they are defined, they cannot be altered or undefined.

A constant is an identifier (name) for a fixed value that remains unchanged throughout the script.

A valid constant name begins with a letter or an underscore (without a $ sign before it).

Note: Unlike variables, constants are automatically global throughout the entire script.

Create a PHP Constant

To define a constant, use the define () function.

Syntax

define(name, value, case-insensitive);

Parameters:

  • name: Indicates the name of the constant.
  • value: Represents the value assigned to the constant.
  • case-insensitive: Determines whether the constant name is treated as case-insensitive. The default setting is false.

Note: Defining case-insensitive constants has been deprecated since PHP 7.3. Starting from PHP 8.0, only false is accepted; using true will trigger a warning.

Define a constant with a case-sensitive name:

<?php
define("HELLO", "Welcome");
echo HELLO;
?>

/*
Output:
Welcome
*/

PHP const Keyword

A constant can also be declared using the const keyword.

To define a constant with the const keyword:

<?php
const FRUIT = "Apple";
echo FRUIT;
?>

/*
Output:
Apple
*/

const cannot be used within block scopes such as functions or if statements.

define() can be used to declare constants even inside block scopes. 

PHP Constant Arrays

Starting with PHP 7, you can create an array constant using the define() function.

Define an array constant:

<?php
define("FRUITS", ["Apple", "Orange", "Banana"]);
echo FRUITS[1];
?>

/*
Output:
Orange
*/

Constants are Global

Constants are globally accessible and can be used throughout the entire script. This example shows how a constant can be accessed within a function, even when it is defined outside the function.

<?php
define("HELLO", "Welcome");

function myFunction() {
  echo HELLO;
}
myFunction();
?>

/*
Output:
Welcome
*/

Questions & Answers