PHP Constants – How To Define And Use In Program


Objective

What are PHP Constants?
How to define Constants in PHP?
Programming Examples

WHAT ARE PHP CONSTANTS?

Most of the time, you need to define a variable with fixed values and that values couldn't be changed in the program. For example, you can define the value of PI as constant. Constants are the variable that is not changeable once defined.

HOW TO DEFINE CONSTANTS IN PHP?

There are some rules when defining constants in PHP.

  1. A constant is created using define keyword.
  2. The name of constant should be a simple string.
  3. It doesn't start with $ (dollar) symbol, unlike variables.
  4. A constant can be case-sensitive or case-insensitive based on the Boolean parameter passed when creating constant.
  5. A constant is global by default.
  6. There are 3 parameters in define.
    define(name, value, case-insensitive)

    name: It is a simple string and it is constant name.
    Value: it is the value of constants.
    Case-insensitive: By default it is false. If you want Constants as case-sensitive, make it true.
PROGRAMMING EXAMPLE
<?php
define("Temp",'35', false);
echo Temp;
$NewTemp=Temp+10;
echo "<br />";
echo $NewTemp;
?>

Output
35
45

SUMMARY

In this tutorial, you learn how to define and use Constants in PHP. Constants are widely used in Mathematical operations and physics numerical where most of the values are constants like values of PI, Gravity, escape velocity etc. In the next chapter you will learn Arrays in PHP.

Back Next