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
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", "https://www.sharequery.com"); //Using constant echo BASE_URL;
The output of the above program will be – https://www.sharequery.com
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;
The output of the above program will be – India