How do you define a constant in php?

Last updated 5 years ago | 1449 views 75     5

Tags:- PHP

Constant in PHP

The define() function is used to defining a constant in PHP

define("GREETING", "Welcome to StudyZone4U.com");
 

Constants are like variables except that once they are defined they cannot be changed or undefined during script execution

A constant is an identifier or name for a value. The value cannot be changed during the script.

Syntex

define(name, value, case-insensitive)

Parameters

  • name: Define the name of the constant
  • value: Define the value of the constant
  • case-insensitive: Define the constant name should be case-insensitive or not. Default is false

Let's see an example of the constant with case-sensitive

<?php

define("GREETING", "Welcome to StudyZone4U.com");

echo GREETING;

?>

//Output

Welcome to StudyZone4U.com

Constant with the case-insensitive name:

<?php

define("GREETING", "Welcome to StudyZone4U.com");

echo greeting;
?>

//Output

Welcome to StudyZone4U.com

 

The main thing about constant is they are automatically global and can be used across the entire script.

<?php

define("GREETING", "Welcome to StudyZone4U.com");

function zone() {
    echo GREETING;
}

zone();

?>

//Output

Welcome to StudyZone4U.com