How to declare a constant in PHP?

by jasen_gottlieb , in category: PHP General , 16 days ago

How to declare a constant in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 13 days ago

@jasen_gottlieb 

In PHP, you can declare a constant using the define() function. The define() function takes two parameters: the name of the constant and its value. Here is an example:

1
2
// Define a constant named PI with the value 3.14159
define('PI', 3.14159);


In this example, the define() function creates a constant named PI with the value 3.14159. Once a constant is defined, it cannot be changed or redefined throughout the execution of the script.


You can then use the constant in your code by referencing its name, like this:

1
2
// Output the value of the constant PI
echo PI;


This will output the value of the constant PI. You can also use constants in expressions, like this:

1
2
3
// Calculate the area of a circle with radius 2 using the constant PI
$area = PI * 2 * 2;
echo $area;


This will output the area of the circle with radius 2, which is calculated using the constant PI.