PHP Constants Example

PHP contains some special constants named as magic constants. These magic constants are not actually constants because of revealing with different values based on the place they are used. The magic constants are case-insensitive.

Defining PHP constants using define()

This code defines PI constant and prints it to the browser using PHP echo statement.

echo PI; // Output: 3.14

In the above program, the constant is defined as a key-value pair. The key is used to get the value of the constant.

In the above program, the define() function gets only two parameters. The define() has an optional third parameter to set the case insensitivity of a constant. By default, the constants are case sensitive. We can make them case insensitive by setting the case insensitivity flag to true. So, the above example code can be changed as,

define("PI",3.14, true);
echo pi; // Output: 3.14

PHP Constants with const

PHP const is a language construct where the define() is a function. We should use static name and value with the const statement to initialize constants where the define() function allows variable interpolation and function call while defining constant. Constants defined using this construct is always case sensitive.

Defining constants using the const statement is good in readability aspect, though the define() has many features by enabling case insensitivity, allowing function call assigning values to the constant, revealing constants at runtime. The following line shows the example of initializing constants using a const statement.

const PI = "3.14";
echo PI; // Output: 3.14

Related Functions to Access Constants


PHP constant() function is used to get the value of the constant by sending its id as an argument of this function. The following example code uses constant() function to get the constant value by using the id.

$id = "PI";
echo constant($constant);


The get_defined_constants() function will dump all user-defined constants and core constants into an array by default. It receives a boolean value as its argument to categorize the constants. If it is set to true, then this function will categorize all built-in constants and user-defined constants with a multidimensional array.

You may also like...

Leave a Reply

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

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By :