How do you define a constant in php?

126 Views

How do you define a constant in php?

Constant in php

The define() function is use to defining a constant in php

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

A 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 name of the constant
  • value: Define 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 constant with case-sensitive

 <?php

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

echo GREETING;

?>

//Output

Welcome to StudyZone4U.com

Constant with 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

 

Tags:-
PHP