PHP Constants


In PHP, a constant is a name or identifier for a simple value that does not change during the execution of a script. Unlike variables, constants do not use the $ symbol and remain immutable once defined. Constants are widely used in web development for configuration settings, fixed mathematical values, and application-wide settings. By using constants, you can make your code more readable, maintainable, and less error-prone.

Defining Constants

You can define constants in PHP using either the define() function or the const keyword. Each method has its own use cases.

Using define()

The define() function defines constants at runtime, making it flexible for dynamic scenarios:

<?php
define("SITE_NAME", "CodePractice"); // Define a constant
echo SITE_NAME; // Outputs: CodePractice
?>
  • Constants are case-sensitive by default.

  • Once defined, a constant cannot be redefined.

define("SITE_NAME", "NewSite"); // Warning: Constant already defined
  • define() can also accept a third parameter to make constants case-insensitive (deprecated in PHP 8.0).

Using const

The const keyword defines constants at compile time:

<?php
const PI = 3.14159;
echo PI; // Outputs: 3.14159
?>
  • const cannot use expressions or function calls, unlike define().

  • const is typically used inside classes or for constant expressions.

Types of Constants

PHP supports several types of constants:

1. String Constants

Strings are the most common constants used for messages, URLs, or labels:

<?php
define("WELCOME_MSG", "Hello, Welcome to CodePractice!");
echo WELCOME_MSG;
?>
  • Strings are immutable; once defined, they cannot change.

2. Integer Constants

Integers are used for limits, counts, or thresholds:

<?php
const MAX_USERS = 100;
echo MAX_USERS;
?>
  • Useful for settings like maximum login attempts or pagination limits.

3. Float Constants

Floats store decimal values for calculations:

<?php
define("PI_VALUE", 3.14159);
echo PI_VALUE;
?>
  • Commonly used in geometry, finance, or scientific applications.

4. Boolean Constants

Booleans represent true/false settings, often used for debugging or feature toggles:

<?php
define("DEBUG_MODE", true);
echo DEBUG_MODE; // Outputs: 1
?>
  • true outputs 1, false outputs an empty string.

Magic Constants

PHP offers magic constants, predefined constants whose values depend on where they are used:

<?php
echo __LINE__ . "<br>";     // Current line number
echo __FILE__ . "<br>";     // Full path of current file
echo __DIR__ . "<br>";      // Directory of current file
echo __FUNCTION__ . "<br>"; // Name of current function
echo __CLASS__ . "<br>";    // Name of current class
?>
  • Magic constants are useful for debugging, logging, and referencing file paths.

  • Example in a class:

<?php
class Sample {
    public function display() {
        echo "Class: " . __CLASS__ . ", Function: " . __FUNCTION__;
    }
}
$obj = new Sample();
$obj->display();
?>

Case-Insensitive Constants

By default, constants are case-sensitive, but define() can create case-insensitive constants:

<?php
define("SITE_TITLE", "CodePractice", true); // Deprecated in PHP 8
echo site_title; // Outputs: CodePractice
?>
  • Using const does not support case-insensitive constants.

  • It is recommended to use uppercase names for all constants to avoid confusion.

Using Constants in Expressions

Constants can be used in mathematical calculations, string concatenation, and logical operations:

<?php
define("PI", 3.14159);
$radius = 5;
$area = PI * $radius ** 2; // Area of a circle
echo "Area: " . $area . "<br>";

const GREETING = "Hello, ";
$name = "Vicky";
echo GREETING . $name; // Outputs: Hello, Vicky
?>
  • Constants make your code more readable and maintainable.

  • They prevent accidental changes to important values.

Arrays as Constants

Since PHP 5.6, you can define array constants:

<?php
define("FRUITS", ["Apple", "Banana", "Cherry"]);
echo FRUITS[0]; // Outputs: Apple
?>
  • Array constants are useful for fixed lists, lookup tables, or configuration values.

  • Example for configuration:

<?php
define("DB_CONFIG", [
    "host" => "localhost",
    "user" => "root",
    "password" => "1234"
]);
echo DB_CONFIG["host"];
?>

Best Practices for Constants

  1. Use all uppercase letters for readability: MAX_USERS, SITE_NAME.

  2. Group related constants for configuration settings in a single file.

  3. Avoid using variables in const; only use literal values.

  4. Use constants instead of hardcoding values in multiple places.

  5. Use magic constants for debugging and file references.

  6. Always document constants to make their purpose clear.

Common Mistakes

  • Attempting to reassign a constant:

define("MAX_USERS", 100);
MAX_USERS = 200; // Error
  • Using const inside functions for dynamic values:

function test() {
    const TEMP = rand(1, 10); // Error
}
  • Confusing constants with variables – constants do not use $.

Real-World Use Cases

  • Configuration settings:

define("SITE_URL", "https://www.codepractice.in");
define("MAX_LOGIN_ATTEMPTS", 5);
  • Mathematical constants:

const PI = 3.14159;
const GRAVITY = 9.8;
  • Feature flags:

define("FEATURE_X_ENABLED", true);
  • Lookup arrays:

define("USER_ROLES", ["admin", "editor", "subscriber"]);

Summary of the Tutorial

  • Constants store immutable values in PHP.

  • Create constants using define() or const.

  • Supported types: string, integer, float, boolean, and arrays.

  • Magic constants: __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__.

  • Constants improve readability, maintainability, and reliability.

  • Arrays can be stored as constants for configuration or fixed lists.

  • Best practices: use uppercase names, group constants, avoid reassignment, and document usage.

Constants are vital for configuration, mathematical calculations, feature toggles, and fixed data. Mastering constants helps build clean, reliable, and maintainable PHP applications.


Practice Questions

  1. Create a PHP script that defines a string constant SITE_NAME with the value "CodePractice" and prints it. Include a comment explaining string constants.

  2. Declare an integer constant MAX_USERS with the value 100 and print it. Include a comment explaining integer constants.

  3. Define a float constant PI with the value 3.14159 and print it. Include a comment explaining float constants.

  4. Create a boolean constant DEBUG_MODE set to true and print it. Include a comment explaining boolean constants.

  5. Define an array constant FRUITS containing "Apple", "Banana", and "Cherry". Print the second element using print_r() or echo. Include a comment explaining array constants.

  6. Write a PHP script that uses a constant PI to calculate the area of a circle with radius $r = 5 and prints the result. Include a comment explaining its use in calculations.

  7. Create a PHP script that uses magic constants __LINE__ and __FILE__ to display the current line number and file path. Include comments explaining magic constants.

  8. Define a constant SITE_URL and use it to display a clickable HTML link. Include a comment explaining practical usage.

  9. Attempt to reassign a constant MAX_USERS after it is defined and observe the error. Include a comment explaining why constants cannot be changed.

  10. Create a PHP script that defines multiple constants for configuration, such as DB_HOST, DB_USER, and DB_PASS, and prints them. Include a comment explaining real-world usage.


Try a Short Quiz.

PHP Constants Quiz

Completed the tutorial? Test yourself with this medium-level quiz and build confidence.


Go Back Top