You are currently viewing Define Constants in PHP and How to Create Constant
  • Post category:PHP

Define Constants in PHP and How to Create Constant

Define Constants in PHP

In this article, we will see PHP constants. If someone asks you to define constants in php, you simply say constant is a named memory location whose value never changes during the execution of a program.

Constant in PHP

A constant variable can be created using two methods. Magic constant is available in PHP. The first method uses the “const” keyword and the second one uses the “define” keyword. Let’s see the syntax of both ways.


//declaration and initialization of a constant
const NAME_OF_CONSTANT = value;

//declaration and initialization of a constant
define("NAME_OF_CONSTANT:, value, bool case_insensitive) : bool;

Define function takes three arguments: “name of constant”, “value” and boolean values either true or false. Whether you want to define a constant as a case insensitive or sensitive and it returns true if a constant is created, otherwise it returns false.

N0te :
No comma-separated variable or constant allowed, like in other languages

Example for const keyword

const PI = 3.14;
echo PI;
PI = 4.43; // error statement, because we created PI value in constant, so we can't change the PI value

Creating constant using define keyword

define("SCREEN_WIDTH", 600);
echo SCREEN_WIDTH, "<br/>";

SCREEN_WIDTH = 400; // error statement
READ ALSO  How to Randomize Array value PHP

Leave a Reply