Open In App

PHP Defining Constants

In a production-level code, it is very important to keep the information as either variables or constants rather than using them explicitly. A PHP constant is nothing but an identifier for a simple value that tends not to change over time(such as the domain name of a website eg. www.geeksforgeeks.org). It is ideal to keep all the constants in a single PHP script so that maintenance is made easier. A valid constant name must start with an alphabet or underscore and requires no ‘$’. It is to be noted, constants are irrespective of their scope i.e constants are automatic of global scope. In order to create a constant in PHP, we must use the define() method.

Syntax:  



bool define(identifier, value, case-insensitivity)

Parameters: The function has two required parameters and one optional parameter.  

Return Type: This method returns TRUE on success and FALSE on Failure.



Note: From PHP 8.0, the constants defined with the help of the define() function may be case-insensitive.

Below are some examples to illustrate the working of the define() function in PHP.

Example 1: Below program illustrates defining case-insensitive constants.




<?php
   
  // Case-insensitive constants
  define("Constant","Hello Geeks!",TRUE);
  echo constant;
  echo Constant;
?>

Output

Hello Geeks!  // Case Insensitive thus value is echoed
Hello Geeks!

Example 2: Below program illustrates defining case-sensitive constants.




<?php
 
  // Case-sensitive constant
  define("Constant","Hello Geeks!");
  echo constant;
  echo Constant;
?>

Output: 

constant   // Case Sensitive thus value not echoed
Hello Geeks! 

The PHP compiler will also throw a warning for the above program along with the output as “PHP Notice: Use of undefined constant constant- assumed ‘constant’ in line 5”. 

Summary


Article Tags :