Value of PHP Constants can not be changed during the execution of the script. PHP Constants is an identifier or name which contains unchanged value.
Constants are like variables but once Constants are defined they cannot be changed or undefined. php variables can be changed any time.php variables can be defined by $ sign when PHP Constants can be defined as per as below two methods.
- define() function
PHP Syntax: define(name, value, case-insensitive);
where,
name parameter is name of the constant.
value parameter is value of the constant.
case-insensitive parameter is whether the constant name should be case-insensitive. Default is false
PHP Code Example :
<?php
define("CONSTNAME", "Learn PHP constant by aryatechno!");
echo CONSTNAME;
?>
Output:
Learn PHP constant by aryatechno!
- const keyword
PHP Syntax: const name = value;
PHP Code Example :
<?php
const VARNAME = "Learn PHP constant by aryatechno!";
echo CONSTNAME;
?>
Output:
Learn PHP constant by aryatechno!
A valid constant name starts with a letter or underscore. There is no $ sign before the constant name.
⇒ Constants are automatically global and can be used across the entire script.
PHP Code Example :
We can access constant inside function even if it is defined outside the function as per as below example.
<?php
define("SHORTDESC", "Welcome to aryatechno tutorials!");
function checkScope() {
echo SHORTDESC;
}
checkScope();
?>
Output:
Welcome to aryatechno tutorials!
Difference between (Constant vs Variables) :
Constants | Variables |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Comments