PHP constants are similar to constant variables in other programming languages. A PHP constant holds a fixed value, which cannot be updated after declaration.
Index
Read Also: PHP Data Types
We can define a constant in PHP using two methods. However, both methods work the same. So, there will be no difference in output or usage.
To create a PHP constant, we can use the define() function. For this, we have to declare its name and value, which we won’t be able to change later. It must begin with a letter or underscore (_) and contain as many letters or numbers.
Syntax
define(name, value, case-insensitive);
Example 1
<?php define("MSG", "Hello Suman"); echo MSG; ?>
Output
Hello Suman
Example 2
Constant with case-insensitive name
<?php define("MSG","Hello Suman",true);//not case sensitive echo MSG."</br>"; echo message; ?>
Output
Hello Suman Hello Suman
The const keyword defines a constant at compile time. The const keyword is not a function; it is a language construct. Constants defined using the const keyword are case sensitive.
Example
<?php const MSG="Hello Suman"; echo MSG; ?>
Output
Hello Suman
In PHP, constants are global and used across the script.
Example
<?php define("HELLO", "Welcome Suman"); function myTest() { echo HELLO; } myTest(); ?>
Output
Welcome Suman
It is another way to print the value of constants using the constant() function instead of using the echo statement. The constant () method returns the constant value and NULL value if the constant is not defined.
Syntax
constant(name);
Example
<?php define("MSG", "Suman"); echo MSG."</br>"; echo constant("MSG"); //both are similar ?>
Output
Suman Suman
Read More: PHP Operators
Constants are useful for storing data that don’t need to change while the PHP program is getting executed. PHP constants are similar to constant variables in other programming languages. A PHP constant holds a fixed value, which cannot be updated after declaration.
We hope you have had a complete understanding of PHP Constants. Do refer to further blogs for the complete modules on other aspects of PHP programming.
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…