How to declare a constant in PHP?

by jasen_gottlieb , in category: PHP General , a year ago

How to declare a constant in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jerad , a year 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.

Member

by orpha , 5 months ago

@jasen_gottlieb 

To declare a constant in PHP, you can use the const keyword. Here is an example:

1
2
// Declare a constant named PI with the value 3.14159
const PI = 3.14159;


In this example, the const keyword is used to declare 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.