Procedure to create a constant variable in PHP

 

PHP Constants

v  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.

v  PHP constants can be defined by 2 ways:

Ø  Using define() function

Ø  Using const keyword

v  Constants are similar to the variable except once they defined, they can never be undefined or changed.

v  They remain constant across the entire program.

v  PHP constants follow the same PHP variable rules. 

v  For example, it can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

v  Use the define() function to create a constant.

v  It defines constant at run time.

v  Syntax of define() function in PHP.

define(name, value, case-insensitive)  

Ø  name: It specifies the constant name.

Ø  value: It specifies the constant value.

Ø  case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case sensitive by default.

Example to define PHP constant using define().

File: constant1.php

<?php  

define("MESSAGE","Hello JavaTpoint PHP");  

echo MESSAGE;  

?>  

Output:

Hello JavaTpoint PHP

PHP constant: const keyword

v  PHP introduced a keyword const to create a constant.

v  The const keyword defines constants at compile time.

v  It is a language construct, not a function.

v  The constant defined using const keyword are case-sensitive.

File: constant4.php

<?php  

const MESSAGE="Hello const by JavaTpoint PHP";  

echo MESSAGE;  

?>  

Output:

Hello const by JavaTpoint PHP

Constant() function

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

Syntax

The syntax for the following constant function:

constant (name)  

File: constant5.php

<?php      

        define("MSG", "JavaTpoint");  

echo MSG, "</br>";  

echo constant("MSG");  

//both are similar  

?>  

Output:

JavaTpoint
JavaTpoint

Comments

Popular posts from this blog

PHP Array Functions

IMPLEMENTATION OF LRU PAGE REPLACEMENT ALGORITHM

Tableau(Line Graphs)