PHP Constant Function


 

PHP Constant Function

This tutorial we will describe about the constant in PHP, how to declare, how to use etc are described in this tutorial. Examples will help you to learn this in depth

This tutorial we will describe about the constant in PHP, how to declare, how to use etc are described in this tutorial. Examples will help you to learn this in depth

Constants:

We use define() function or const keyword to define a constant. Only scalar data (boolean, integer, float, and string ) can be declared as constants. A resource can be declared as constant but it is not advisable because unexpected result could occur.

Unlike the variables we do not need to prepend $ sign before a constant. To print a constant we just need to mention the name of the constant.

 

PHP Constant Example:

<?php

define("pi",3.14);

echo "Output of pi is :".pi."<br/>";

echo "If we would like to print constant within \"\" sign output would be: pi <br/> ";

echo "Since pi is a constant, we need not to use '$' sign before constant";

?>

Output:

Output of pi is :3.14
If we would like to print constant within "" sign output would be: pi
Since pi is a constant, we need not to use '$' sign before constant

Example:

<?php

const ab="324";

const ab="32";

echo ab;

?>

Output:

324

 

As in the above example though we want to assign another value to the constant, but the output would be the first value of the variable.

Ads