PHP Constants

Constants are similar to variables, but once defined, they cannot be changed or undefined.

PHP Constants

Constants are identifiers (names) for single values. The value cannot be changed in the script.

Valid constant names start with a letter or underscore (there is no $ symbol before the constant name).

Note:Unlike variables, constants are automatically global throughout the script.

Set PHP Constants

To set a constant, use define() Function - it uses three parameters:

  1. The first parameter defines the name of the constant
  2. The second parameter defines the value of the constant
  3. The optional third parameter specifies whether the constant name is case-insensitive. The default is false.

The following example creates aCase-sensitive Constantswith the value "Welcome to codew3c.com!":

Example

<?php
define("GREETING", "Welcome to codew3c.com!");
echo GREETING;
?>

Run Example

The following example creates aCase-insensitive Constantswith the value "Welcome to codew3c.com!":

Example

<?php
define("GREETING", "Welcome to codew3c.com!", true);
echo greeting;
?>

Run Example

Constants are global

Constants are automatically global and can be used throughout the entire script.

The following example uses a constant within a function, even if it is defined outside the function:

Example

<?php
define("GREETING", "Welcome to codew3c.com!");
function myTest() {
    echo GREETING;
}
myTest();
?>

Run Example