php
  1. php-constants

PHP Constants

In PHP, a constant is an identifier (name) for a simple value that cannot be changed during the execution of the script.

Syntax

A constant is defined using the define() function, which takes two parameters:

  • The name of the constant
  • The value of the constant
define(name, value, case-insensitive);
  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Optional, if set to true, the constant becomes case-insensitive

Example

define("GREETING", "Hello, World!");

echo GREETING;

Output:

Hello, World!

Explanation

In the above example, we defined a constant GREETING with the value "Hello, World!". We then used the echo statement to print the value of the constant.

Constants are useful when you need to define a value that will not change throughout the execution of the script. Constants are also useful for making the code more readable and maintainable.

Use

Constants are useful when you need to define values that should not be changed during the execution of the script.

For example, you can use a constant to define the value of Pi:

define("PI", 3.14159);

$radius = 10;
$area = PI * $radius * $radius;

echo "The area of a circle with radius $radius is $area";

Output:

The area of a circle with radius 10 is 314.159

In the above example, we defined a constant PI with the value 3.14159. We then used the constant to calculate the area of a circle.

Important Points

  • Constants are defined using the define() function.
  • Constants are case-sensitive by default, but you can make them case-insensitive by setting the third parameter of the define() function to true.
  • Constants cannot be redefined or undefined once they are defined.
  • Constants can hold scalar values such as strings, integers, and floats, but cannot hold arrays or objects.

Summary

In PHP, constants are identifiers for simple values that cannot be changed during the execution of the script. Constants are defined using the define() function and can hold scalar values such as strings, integers, and floats. Constants are useful when you need to define values that should not be changed throughout the execution of the script. Constants are case-sensitive by default, but you can make them case-insensitive by setting the third parameter of the define() function to true.

Published on: