PHP Const Keyword
The const
keyword in PHP is used to define constants which are similar to variables but their values cannot be changed throughout the program. Constants are useful in situations where you need to define a value that does not change such as a mathematical constant, like π
.
Syntax
The syntax for defining a constant in PHP using const
is:
const CONSTANT_NAME = constant_value;
Example
<?php
const PI = 3.14;
const NAME = "John Doe";
echo PI; // Output: 3.14
echo NAME; // Output: John Doe
?>
Output
In the example above, the output of PI
and NAME
are printed on the screen.
Explanation
In PHP, a constant is defined using the const
keyword followed by the constant name and its value. Once defined, the value of a constant cannot be changed. Constants are different from variables in that variables can be changed throughout the program, whereas constants cannot.
Use
Constants are useful in a lot of different situations, such as:
- Defining mathematical constants throughout your program
- Defining configuration parameters that need to be fixed
- Defining database connection details
Important Points
- A constant's value cannot be changed throughout the program.
- Constants are always global.
- Constants can only be defined using the
const
keyword or thedefine
function.
Summary
The const
keyword in PHP is used to define constants that have a fixed value throughout the program. Constants are useful when you need to define a value that does not change, such as a mathematical constant or configuration parameter. Once defined, a constant cannot be changed, and it is always global.