EZ

Eduzan

Learning Hub

Eduzan
Eduzan / PHP

PHP Constants

Constants in PHP are identifiers or names that are assigned fixed values, which cannot be changed during the program’s execution. Once a constant is defined, it cannot be undefined or redefined.

By convention, constant identifiers are written in uppercase letters. By default, constants are case-sensitive. A constant name must not start with a number; it should begin with a letter or an underscore, followed by letters, numbers, or underscores. Special characters (other than underscores) should be avoided.

Creating a Constant using define() Function

The define() function in PHP is used to create a constant. Here’s the syntax:

Syntax:

define( 'CONSTANT_NAME', value, case_insensitive )

Parameters:

  • name: The name of the constant.
  • value: The value assigned to the constant.
  • case_insensitive: Defines whether the constant should be case-insensitive. The default is false (case-sensitive).

Example: Creating constants using define() function

<?php

// Creating a case-sensitive constant
define("SITE_TITLE", "LearnPHP");
echo SITE_TITLE . "\n";

// Creating a case-insensitive constant
define("GREETING", "Hello, World!", true);
echo greeting;

?>

Output:

LearnPHP
Hello, World!

Creating a Constant using const Keyword

The const keyword is another way to define constants, mainly used inside classes and functions. Unlike define(), constants created using const cannot be case-insensitive.

Syntax:

const CONSTANT_NAME = value;

Example:

<?php
const MAX_USERS = 100;
echo MAX_USERS;
?>

Output:

100

Constants are Global

Constants in PHP are global by default, meaning they can be accessed anywhere within the script, both inside and outside of functions or classes.

Example: Global access to constants

<?php

define("APP_VERSION", "1.0.5");

function displayVersion() {
    echo APP_VERSION;
}

echo APP_VERSION . "\n";
displayVersion();

?>

Output:

1.0.5
1.0.5

Difference Between Constants and Variables

Though both constants and variables store values, they differ in several aspects:

PHP Constants
FeatureConstantsVariables
SyntaxNo dollar sign ($)Starts with a dollar sign ($)
ValueImmutable (cannot change)Mutable (can be changed)
Case SensitivityCase-sensitive (by default)Case-sensitive
ScopeAlways globalScope can vary (local or global)
Declaration Methoddefine() or constUse of $ symbol
End of lesson.