HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Constants

A constant is an identifier (name) for a simple value. As the name suggests, the value cannot be changed during the execution of the script. Constants are automatically global across the entire script.


1. How to Define a Constant

Unlike variables, constants do not have a dollar sign ($). There are two ways to create a constant: using the define() function or the const keyword.

Using define()

The define() function takes two main parameters: the name of the constant and its value.

<?php
    define("GREETING", "Welcome to RedoHub!");
    echo GREETING;
?>

Using the const Keyword

The const keyword is often used within classes, but it can also be used in the global scope. It is simpler but has some limitations compared to define().

<?php
    const SITE_NAME = "RedoHub";
    echo SITE_NAME;
?>

2. Constant Arrays

In PHP 7+, you can also create constant arrays using the define() function.

<?php
    define("CARS", [
        "Alfa Romeo",
        "BMW",
        "Toyota"
    ]);
    echo CARS[0];
?>

3. Constants are Global

Unlike variables, constants are automatically global. They can be accessed from anywhere in the script, including inside functions, without using the global keyword.

<?php
    define("DATABASE", "users_db");

    function myTest() {
        echo DATABASE; // Accessible here!
    }

    myTest();
?>
Naming Convention: By convention, constant names are written in ALL UPPERCASE. This helps distinguish them from variables at a glance.

4. Magic Constants

PHP provides many "Magic Constants" that change depending on where they are used. They all start and end with double underscores.

Constant Description
__LINE__ The current line number in the file.
__FILE__ The full path and filename of the file.
__DIR__ The directory of the file.
__FUNCTION__ The name of the current function.
Pro Tip: Use constants for values that should never change, such as database credentials, API keys, or version numbers.

Key Points to Remember

  • Constants do not use a dollar sign ($).
  • The value of a constant cannot be changed after it is set.
  • Use define() or the const keyword to create them.
  • Constants are globally accessible throughout your script.
  • Standard practice is to use UPPERCASE_NAMES for constants.
  • Magic constants provide metadata about your script at runtime.