Open In App

How to declare a Constant Variable in PHP?

Creating constants in PHP allows us to define values that remain unchanged throughout the execution of a script. This is particularly useful for storing configuration settings, such as database credentials or API keys, as well as for defining global variables that should not be altered during runtime.

Note: In PHP, the two methods mentioned earlier (define( ) and const) are the primary ways to create constants.



Using the define() function:

It allows defining constants with a function call, accepting two arguments for the constant name and value. Global scope.

define("PI", 3.14);
echo PI;

// Outputs: 3.14

Using the const keyword

It declares class constants or global constants within a file, offering a more concise syntax and being restricted to compile-time constant expressions.



const CONSTANT_NAME = "constant_value";

Features

Article Tags :