What is Constant in PHP?


What is Constant in PHP?
A constant is an identifier for a data value. Once defined, the data value identified by a constant can’t be changed.
PHP supports constants with following basic rules:

A constant must be defined with the define(name, value).
For example, define(“PI”, 3.14); defines a constant named as PI to a value of 3.14.

To retrieve the value defined in a constant, you can use the constant name directly in any expression.
For example, define(“PI”, 3.14); $area = PI * $radius * $ radius; uses the value define in PI to calculate the area.

You are allowed to use any string for the constant name.
For example, define(“LONG PI”, 3.1415); defines a constant named as “LONG PI” to a value of 3.1415. But using special characters in constant names are not recommended.

If a constant name contains a special characters, you need to use the constant(name) function to retrieve the value defined in the constant.
For example, define(“LONG PI”, 3.1415); $area = constant(LONG PI) * $radius * $radius; uses the value defined in “LONG PI” to calculate the area.

If you want to know if there is constant for a given constant name, you can use the define(name) function.
For example, define(“LONG PI”, 3.1415); defined(“LONG PI”); returns TRUE. And defined(“LONG MI”); returns FALSE.

Now let’s take an example to confirm some rules mentioned above.
Click here to download example file.
What is Constant in PHP? What is Constant in PHP? Reviewed by Abdul iTech on Thursday, March 07, 2019 Rating: 5

No comments:

Powered by Blogger.