PHP Constants
A PHP constant is a named identifier (name) that holds a fixed value throughout your script's execution. Unlike variables, constants cannot be changed once defined.
• Improved code readability and maintainability: Meaningful names for constants enhance code comprehension and reduce errors.
• Increased efficiency: Predefined values can be accessed faster than calculated values.
• Enhanced security: Sensitive information can be stored securely in constants instead of hardcoded variables.
• Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive);
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive.
Example
Create a constant with a case-sensitive name:
<!DOCTYPE html> <html> <body> <?php // case-sensitive constant name define("GREETING", "Welcome to codelines!"); echo GREETING; ?> </body> </html>
Output
Welcome to codelines!
Example
Create a constant with a case-insensitive name:
<!DOCTYPE html> <html> <body> <?php // case-sensitive constant name define("GREETING", "Welcome to codelines!"); echo GREETING; ?> </body> </html>
Output
Welcome to codelines!
• PHP const Keyword
You can also create a constant by using the const keyword.
Example
Create a constant with the const keyword:
<!DOCTYPE html> <html> <body> <?php const MYCAR = "Codelines!"; echo MYCAR; ?> </body> </html>
Output
Codelines!
const vs. define()
• const are always case-sensitive
• define() has has a case-insensitive option.
• const cannot be created inside another block scope, like inside a function or inside an if statement.
• define can be created inside another block scope.
• PHP Constant Arrays
From PHP7, you can create an Array constant using the define() function.
Example
<!DOCTYPE html> <html> <body> <?php define("cars", [ "Alfa Romeo", "BMW", "Toyota" ]); echo cars[0]; ?> </body> </html>
Output
Alfa Romeo
• Constants are Global
This example uses a constant inside a function, even if it is defined outside the function:
Example
<!DOCTYPE html> <html> <body> <?php define("GREETING", "Welcome to Codelines.in!"); function myTest() { echo GREETING; } myTest(); ?> </body> <html>
Output
Welcome to Codelines.in!