Constants in PHP

PHP constants are identifier or name that can't be changed during the execution of the script. Constants are automatically global across the entire script. A valid constant name starts with a letter or underscore but constants should be defined in uppercase letters.. PHP constants can be defined by two ways :
  • Using define() function

  • Using const keyword

PHP constants using define() function :

Let's see the basic syntax of define() function in PHP.
define(name, value, case-insensitive)

Parameters :
  1. name : Specifies the name of the constant
  2. value : Specifies the value of the constant
  3. case-insensitive : Default value is false. It means it is case sensitive by default.
The example below creates a constant with a case-sensitive name :
<?php
define("MESSAGE","Example of PHP constants.");
echo MESSAGE;
?>

Output :
Example of PHP constants.

The example below creates a constant with a case-insensitive name :
<?php
define("MESSAGE","Example of PHP constants.",true);
echo message;
?>

Output :
Example of PHP constants.

PHP constants using const keyword :

It is faster than define() and case sensitive.
<?php 
const MESSAGE="Example of const by Neoogy"; 
echo MESSAGE; 
?>

Output :
Example of const by Neoogy

0 Comments