Getting Started with PHP Constants


Understanding PHP Constants

PHP constants are used to store values that cannot be changed during the script execution. Constants are globally accessible throughout the script, and they do not require a dollar sign ($) prefix like variables.

1. Defining Constants: define()

The define() function is used to define a constant in PHP. Once defined, the constant's value cannot be changed.

<?php
define("PI", 3.14159);  // Defining a constant
echo "The value of PI is: " . PI . "<br>";
?>

Output:

The value of PI is: 3.14159

2. Case Sensitivity of Constants

By default, constants in PHP are case-sensitive. You can make them case-insensitive by setting the third parameter of define() to true.

<?php
define("GREETINGS", "Hello, AIT!", true);  // Case-insensitive constant
echo GREETINGS . "<br>";  // Works with any case
echo greetings . "<br>";  // Also works with lowercase
?>

Output:

Hello, AIT!

Hello, AIT!

3. Predefined Constants

PHP provides several built-in constants, such as PHP_VERSION, PHP_OS, and others.

<?php
echo "PHP Version: " . PHP_VERSION . "<br>";
echo "Operating System: " . PHP_OS . "<br>";
?>

Output:

PHP Version: 8.0.0

Operating System: Linux

Constants are ideal for values that should remain unchanged throughout the execution of the program, such as configuration values or mathematical constants.