PHP constants have a fixed value and it can not be changed during the execution of the script. It will be created using the define()
function or const
keyword.
In other words, a PHP constant is an identifier(name) that has a fixed value and it can not be changed or undefined except the magic constant.
$
sign before the constant
name
(_)
.
PHP constant can be defined in two ways.
define()
functionconst
keyword
To create a PHP constant function, use the define()
function. It defines constant at the run time.
define(name, value, case-insensitive);
name:
It refers to a constant name.value:
It denotes constant value.case-insensitive:
Its default value is false. It denotes that the constant name is case-sensitive by default..Source Code
<?php
define("WEBSITE","sudhakarinfotech");
echo WEBSITE;
?>
PHP provides another way to create a constant using the const
keyword. Please keep in mind that the const
keyword defines constant at compile-time and the constant name is also case-sensitive.
Source Code
<?php
const WEBSITE="Learn PHP from sudhakarinfotech";
echo WEBSITE;
?>
Let us create an array constant using the the define()
function.
Source Code
<?php
define("cars", [
"Honda City",
"BMW",
"Maruti Suzki"
]);
echo cars[0];
?>
There are two ways to display the constant value on the screen(browser).These are
echo
Constant()
functionTo display constant value, PHP also introduces a constant()
function that is used to display the value of the constant.
constant(ConstantName)
Source Code
<?php
define("WEBSITE", "SUDHAKARINFOTECH");
echo WEBSITE, "</br>";
echo constant("WEBSITE");
//both are similar
?>
($)
before the name while the constant
name does not have a $
sign before the constant
name.