PHP Constants PHP

PHP Constants  

PHP Constants

PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script. PHP constants can be defined by 2 ways:

  1. Using define() function
  2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Let's see the syntax of define() function in PHP.

  1. define(name, value, case-insensitive)  
  1. name: specifies the constant name
  2. value: specifies the constant value
  3. case-insensitive: Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

  1. <?php  
  2. define("MESSAGE","Hello RedhuntStudy PHP");  
  3. echo MESSAGE;  
  4. ?>  

Output:

Hello RedhuntStudy PHP

File: constant2.php

  1. <?php  
  2. define("MESSAGE","Hello RedhuntStudy PHP",true);//not case sensitive  
  3. echo MESSAGE;  
  4. echo message;  
  5. ?>  

Output:

Hello RedhuntStudy PHPHello JavaTpoint PHP

File: constant3.php

  1. <?php  
  2. define("MESSAGE","Hello RedhuntStudy PHP",false);//case sensitive  
  3. echo MESSAGE;  
  4. echo message;  
  5. ?>  

Output:

Hello RedhuntStudy PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

 

PHP constant: const keyword

The const keyword defines constants at compile time. It is a language construct not a function.

It is bit faster than define().

It is always case sensitive.

File: constant4.php

  1. <?php  
  2. const MESSAGE="Hello const by JavaTpoint PHP";  
  3. echo MESSAGE;  
  4. ?>  

Output:

Hello const by JavaTpoint PHP

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries