Constants in PHP, are the values which cannot be changed, once assigned, during program execution. In PHP, constants can be created in two ways:
- define(name, value)
- const keyword
Constants should be in uppercase by convention and also they are case-sensitive by default.
Constant with define()
define() takes two Parameters
define Parameters | Description |
---|---|
name | It is constant name, it is used to access constant value should be in uppercase. |
value | it is the constant value. |
Syntax
define(name, value);
Example
<?php
define("MYCONSTANT", "Hello from yourshala");
echo MYCONSTANT;
?>
const keyword
Defining constant with const keyword is like define a normal variable with const keyword. only difference between const and normal variable is, with const variable, value cannot be changed throughout the program.
Syntax
const CONSTANT_NAME = value;
Value must be assigned to const, other wise it gives error.
Example
<?php
const MYCONSTANT = "Hello from yourshala";
echo MYCONSTANT;
?>
Constants scope is global by-default it means constant can be accessed anywhere in PHP script.
<?php
define("MYCONSTANT", "Hello from define()");
const CONST_PHP = "Hello from const keyword";
function test(){
echo MYCONSTANT . "<br/>";
echo CONST_PHP;
}
test();
?>
Difference between define() and const
define() | const |
---|---|
define constants can be created and used inside blocks like if, else, for, while, do-while loops etc. | const keyword constant cannot be created and used inside blocks like if, else, for, while, do-while loops etc. |
Example
with define()
<?php
for($a=0; $a <= 5; $a++){
define("MYCONSTANT", "Hello from yourshala PHP");
echo MYCONSTANT;
}
?>
Output:
Hello from yourshala PHP
Hello from yourshala PHP"
Hello from yourshala PHP"
Hello from yourshala PHP"
Hello from yourshala PHP"
With const keyword
<?php
for($a=0;$a <= 20;$a++){
const MYCONSTANT = "Hello from PHP";
echo MYCONSTANT;
}
?>
Output: Parse error: syntax error, unexpected token "const"
<?php
$a = 20;
if($a == 20){
const MYCONSTANT = "Hello from PHP";
echo MYCONSTANT;
}
?>
Output: Parse error: syntax error, unexpected token "const"