In PHP, a constant is an identifier for a simple value that cannot change during the execution of the script. Unlike variables, constants are automatically global across the entire script and can be defined using the define() function or the const keyword. This tutorial will cover how to define and use constants in PHP.
Constants in PHP are useful when you need a value that should remain unchanged throughout your application. They help improve code readability, maintainability, and prevent accidental modification of values that should not change.
There are two primary ways to define constants in PHP:
Using define() Function:
The define() function is used to create a constant with the specified name and value. It takes three parameters:
Using const Keyword:
The const keyword can be used to define constants within classes or at the global scope. Constants defined with const are always case-sensitive.
Once a constant is defined, it can be accessed anywhere in your script without needing to declare it again. Constants are automatically global and do not require the $ symbol before their name.
Let's look at some practical examples of defining and using constants in PHP.
define()<?php
// Define a constant using define()
define("SITE_NAME", "CodingStuff.io");
// Accessing the constant
echo SITE_NAME; // Outputs: CodingStuff.io
// Define a case-insensitive constant
define("PI", 3.14, true);
// Accessing the constant in different cases
echo pi; // Outputs: 3.14
echo Pi; // Outputs: 3.14
echo PI; // Outputs: 3.14
?>
const Keyword<?php
// Define a constant at the global scope using const
const MAX_USERS = 100;
// Accessing the constant
echo MAX_USERS; // Outputs: 100
// Define a constant within a class
class Config {
const DB_HOST = "localhost";
}
// Accessing the constant from the class
echo Config::DB_HOST; // Outputs: localhost
?>
<?php
const TAX_RATE = 0.08;
$price = 100;
$totalPrice = $price + ($price * TAX_RATE);
echo "Total Price: $" . $totalPrice; // Outputs: Total Price: $108
?>
Now that you have learned about constants in PHP, the next step is to explore Operators in PHP. Operators are essential for performing operations on variables and values, enabling complex logic and calculations in your applications.