-
Hajipur, Bihar, 844101
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.
You can define constants in PHP using either the define() function or the const keyword. Each method has its own use cases.
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).
constThe 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.
PHP supports several types of 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.
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.
Floats store decimal values for calculations:
<?php
define("PI_VALUE", 3.14159);
echo PI_VALUE;
?>
Commonly used in geometry, finance, or scientific applications.
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.
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();
?>
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.
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.
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"];
?>
Use all uppercase letters for readability: MAX_USERS, SITE_NAME.
Group related constants for configuration settings in a single file.
Avoid using variables in const; only use literal values.
Use constants instead of hardcoding values in multiple places.
Use magic constants for debugging and file references.
Always document constants to make their purpose clear.
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 $.
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"]);
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.
Create a PHP script that defines a string constant SITE_NAME with the value "CodePractice" and prints it. Include a comment explaining string constants.
Declare an integer constant MAX_USERS with the value 100 and print it. Include a comment explaining integer constants.
Define a float constant PI with the value 3.14159 and print it. Include a comment explaining float constants.
Create a boolean constant DEBUG_MODE set to true and print it. Include a comment explaining boolean constants.
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.
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.
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.
Define a constant SITE_URL and use it to display a clickable HTML link. Include a comment explaining practical usage.
Attempt to reassign a constant MAX_USERS after it is defined and observe the error. Include a comment explaining why constants cannot be changed.
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.