Open In App

How to declare a Constant Variable in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Immutable Values: Once defined, constants cannot be changed or redefined elsewhere in the script.
  • Accessing Constants: Constants are accessed without the leading $ symbol. Example: echo CONSTANT_NAME;
  • Convention: By convention, constant names are usually uppercase.
  • Usage: Constants are commonly used for storing configuration values, such as database credentials or API keys, that remain constant during script execution.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads