PHP

Constant in PHP-

  • A constant is an identifier for a simple value.
  • The constant value cannot change during the execution of the script (except for magic constants, which aren't actually constants).
  • A constant is case-sensitive by default.
  • By convention, constant identifiers are always uppercase.
  • The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Creating a PHP Constant-

To create a constant, use the define() function.

Syntax-

define(name, value, case-insensitive)
Parameters:

name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

The example below creates a constant with a case-sensitive name:

Example-

<?php

// Valid constant names
define("PI", "3.14");
define("MESSAGE", "Data saved successfully.");
define("ERROR_MESSAGE", "Error! data could not be saved.");

echo MESSAGE;

?>

 

Note- The scope of a constant is global. You can access constants anywhere in your script without regard to scope.

Back to Top