PHP Constants

PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways:

Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

Note: Unlike variables, constants are automatically global throughout the script.

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function in PHP.

Use the define() function to create a constant. It defines constant at run time. Let's see the syntax of define() function in PHP.

define(name, value, case-insensitive)

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

File: constant1.php


<?php  
define("MESSAGE","Hello Shorat PHP");  
echo MESSAGE;  
?>  
            

Output

Hello Shorat PHP

Create a constant with case-insensitive name:

File: constant2.php


<?php    
define("MESSAGE","Hello Shorat PHP",true);//not case sensitive    
echo MESSAGE, "</br>";    
echo message;    
?>    
            
            

Output

Hello Shorat PHP Hello Shorat PHP

File: constant3.php


<?php  
define("MESSAGE","Hello Shorat PHP",false);//case sensitive  
echo MESSAGE;  
echo message;  
?>  
            
            

Output

Hello Short PHP Notice: Use of undefined constant message - assumed 'message' in C:wampwwwvconstant3.php on line 4 message

PHP constant: const keyword

PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.

File: constant4.php


?php  
const MESSAGE="Hello const by Shorat PHP";  
echo MESSAGE;  
?>  
            

Output

Hello const by Shorat PHP

The syntax for the following constant function:

Constant() function

There is another way to print the value of constants using constant() function instead of using the echo statement.

Syntax


constant (name)
            

PHP Example


<?php      
define("MSG", "Shorat");  
echo MSG, "</br>";  
echo constant("MSG");  
//both are similar  
?>  
            

Output

Shorat Shorat
Constants Variables
String represents sequence of characters e.g. "hello"
Number represents numeric values e.g. 100
Boolean represents boolean value either false or true
Undefined represents undefined value
Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description
Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression