How to declare a constant in PHP?

by jasen_gottlieb , in category: PHP General , 2 years ago

How to declare a constant in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

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

Related Threads:

How to declare a variable in PHP?
How to declare a abstract const in php?
How to declare an array of specific type in php?
How to declare an empty variable inside function in php?
How to define dynamic values as constant in laravel?
How to redirect after 5 seconds in PHP?