The Wayback Machine - https://web.archive.org/web/20250404084905/https://www.geeksforgeeks.org/php-constants/
Open In App

PHP Constants

Last Updated : 01 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Constants in PHP are identifiers or names that can be assigned any fixed values and cannot change during the execution of a program. They remain constant throughout the program and cannot be changed during the execution. Once a constant is defined, it cannot be undefined or redefined.

By convension, constant identifiers are always written in upper case. By default, a constant is always case-sensitive. A constant name must never start with a number. It always starts with a letter or underscores, followed by letter, numbers or underscore. It should not contain any special characters except underscore, as mentioned.

Creating a Constant using define() Function

The define() function in PHP is used to create a constant as shown below:

Syntax

define( 'CONSTANT_NAME', value, case_insensitive )

The parameters are as follows:

  • name: The name of the constant.
  • value: The value to be stored in the constant.
  • case_insensitive: Defines whether a constant is case insensitive. By default this value is False, i.e., case sensitive.

Example: Creating constants using define() function.

PHP
<?php

// This creates a case-sensitive constant
define("WELCOME", "GeeksforGeeks");
echo WELCOME . "\n";

// This creates a case-insensitive constant
define("HELLO", "GeeksforGeeks", true);
echo hello;

?>

Output
GeeksforGeeks
GeeksforGeeks

Creating a Constant using const Keyword

The const keyword is another way to define constants but is typically used inside classes and functions. The key difference from define() is that constants defined using const cannot be case-insensitive.

Syntax

const CONSTANT_NAME = value;

Example:

PHP
<?php
const SITE_NAME = 'GeeksforGeeks';
echo SITE_NAME;
?>

Output
GeeksforGeeks

Constants are Global

By default, constants are global, and can be used throughout the script, accessible inside and outside of any function.

Example: Constants are global and accessible inside and outside of the block.

PHP
<?php

define("WELCOME", "GeeksforGeeks");

function testGlobal() {
    echo WELCOME;
}
 
echo WELCOME . "\n";
testGlobal();

?>

Output
GeeksforGeeks
GeeksforGeeks

Difference Between Constants and Variables

Although both constants and variables are used to store values, they differ in several ways:

FeatureConstantsVariables
SyntaxNo dollar sign ($)Starts with a dollar sign ($)
ValueImmutableMutable
Case SensitivityCase-sensitive (default)Case-sensitive
Global ScopeAlways globalScope can vary (local or global)
Declaration Methodsdefine() or constUse of $ symbol

Next Article

Similar Reads

three90RightbarBannerImg