Constants are like variables, but when once they are defined they can't be changed or undefined.
What is Constant in PHP
A constant is a name or an identifier for a specific value. The value can’t be changed during the script. A valid constant name must begin with a letter of the alphabet or underscore (_
).
Here’re some important Rules for PHP Constant Variable Declaration:
- A valid constant name must begin with a letter of the alphabet or underscore (
_
). - A constant name dollar (
$
) sign cannot be used.
Constant data is very useful for saving, which does not change the running of the script. Common examples of such information include configuration options such as database usernames and passwords, website’s main URL, company name etc. A few examples follow:
Code Example:
<?php
// Defining constant
define("SITE_URL", "https://www.coderwell.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
This returns the following:
Thank you for visiting – https://www.coderwell.com/
Defining a Constant
The define()
function defines a constant by assigning a value to a name. Its prototype follows:
To create a constant, using the define()
function. Its prototype follows:
Syntax
string name
, mixed value
, [bool case_insensitive]
)
Parameters:
String name
: Declare the name of the constantMixed value
: Declare the value of the constantCase-insensitive
: The constant name is case-sensitive. The default is false
When Constant is case-sensitive
Creates a constant with a case-sensitive name. Below the example.
Code Example:
<?php
define("GREETING", "Welcome to Coderwell.com!");
echo GREETING;
?>
This returns the following:
Welcome to Coderwell.com!
When Constant is case-insensitive
creates a constant with a case-insensitive name. Below the example.
Code Example:
<?php
define("GREETING", "Welcome to Coderwell.com!", true);
echo greeting;
?>
This returns the following:
Welcome to Coderwell.com!