PHP Constants

Constant is a named memory location whose value never change during the execution of a program. Constant once defined remains unchanged throughout the execution of a script except magic constants.

Constant value is very useful to keep values throughout the script execution. Most commonly we define database name, username, website baseurl etc as a contant value.

A constant value is defined using a define() function.

Declaring & Initialization of a Constant

define("name", "value");

Naming Conventions for PHP Constants

A valid constant name start with a letter or underscore(“_”) and followed by any number of letters, numbers or underscore.
– There is no any sign ($) before the constant name.
– Unlike variable, constant is globally access in entire script.

Let’s understand by example –

//Defining constant
define("BASE_URL", "");

//Using constant
echo BASE_URL;

The output of the above program will be –

PHP Constant Arrays

In PHP 7, you can also create array constant using define() function.
Let’s have a look how to create array constant –

//Defining constant array 
define("countries", ["India", "Australia", "Canada"]);
//Using constant
echo countries[0];

The output of the above program will be – India

Trending Topics