Home » PHP » PHP Constants
The tutorial helps you learn about PHP constants. We will first understand what PHP Constants is.
The variables whose values cannot be changed are called constants. In simple words, if the value for the constant is set once, it cannot be changed.
In PHP, a constant can be defined by using two methods:
Another point to remember is that you don't have to use the $ symbol with the constant's name while naming a constant.
The syntax for using the define() function for creating a constant is mentioned below.
define(name, value, case-insensitive)
Parameters:
Check below example
In the example given below, the parameter case-insensitive has not been mentioned; hence it will automatically take the default value.
<?php
define(BLOG, "www.readytocode.net");
echo BLOG;
?>
Output:
www.readytocode.net
For the above constant definition, in case we try to use the following statement, then we will get an error, the reason being the constant PHP is case sensitive.
<?php
define(BLOG, "www.readytocode.net");
echo blog;
?>
Output:
error:
It will be considered as a string by echo, and it will print it as it is, with a little NOTICE stating that the string variable is not defined.
Now let's take another example where we specify the case-insensitive parameter.
<?php
define(PHP, "Very well, free written PHP tutorial.", true);
echo php;
?>
Output:
Very well, freewritten PHP tutorial.
Constants in PHP can also be defined using the const keyword. But the const keyword can only be used to define scalar constants, i.e., only floats, integers, strings, and booleans, while you can use define() for defining array and resource constants also, although they are not used often.
<?php
const PHP = "Very well, freewritten PHP tutorial.";
echo PHP;
?>
Output:
Very well, freewritten PHP tutorial.
Note:- When a constant is defined using the const keyword, the constant name is always case sensitive.