How to create a constant in PHP?

By Faruque Ahamed Mollick

In PHP, a constant is an identifier or simply a name that store value. the constant value can not be changed during the script.

Constants can be defined and then accessed anywhere in the script without regard to variable scoping rules. After a constant set, it can’t be redefined or undefined.

Create a directory if it does not exists in PHP

How to replace particular characters of a string in PHP?

Now we are going to see how to create a constant in PHP.

PHP has an inbuilt function to create a constant. Below is an example:

<?php
define("MY_MESSAGE", "This is my message!");
echo MY_MESSAGE;
?>

The above code will return the result that you can see below:

This is my message!

So we can see that a constant is very similar to a variable. But there is the difference between constant and variables. Constants are automatically set to global and can be used across the entire script. But in case of variables, it needs to defined as global.

In default, the created constant always be case sensitive. But we can always set the case sensitivity to case insensitive. Below is the syntax:

define(name, value, CASE_SENSITIVITY)

The case sensitivity can set to boolean value.

If we want to create a constant with case-insensitive, then below is the example code:

<?php
define("MY_MESSAGE", "This is my message!", true);
echo MY_MESSAGE;
?>

From the example below, we can understand that the PHP constant is global by default:

<?php
define("MY_MESSAGE", "This is my message!", true);

function myFunction() {
    echo MY_MESSAGE;
}
 
myFunction();
?>

The above code will return the result below:

This is my message!

From the above result, we can understand that the constant also works inside the function. That’s means a PHP constant is always global by default.

Force Download A File From Server In PHP

Leave a Reply

Your email address will not be published. Required fields are marked *