What are constants and how to define them in PHP?

A constant is a value cannot change during the execution of the program. By default, it is case-sensitive. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. 

If you have defined a constant, it can never be changed or undefined. 

To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically.

Constants are automatically global and can be used across the entire script.

To create a constant, use the define() function.

Syntax:
define(name, value, case-insensitive)

Parameters:

  • name: Specifies the name of the constant.
  • value: Specifies the value of the constant.
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.

Example:

<!DOCTYPE html>

<html>

<body>

<?php

case-insensitive constant name

define("GREET", "Welcome to tutu’rself!", true);

echo greet;

?>

</body>

</html>

 

Output:

Welcome to tutu’rself!


FOLLOW US ON LinkedIn



Explore Tutu'rself