PHP - Introduction Constants

Introduction

You can define constants in PHP.

The values of constants can never be changed.

Constants can be defined only once in a PHP program.

Constants' names do not start with the dollar sign.

It's good practice to use all-uppercase names for constants.

You should avoid naming your constants using any of PHP's reserved words.

Constants may only contain scalar values such as Boolean, integer, float, and string.

They can be used from anywhere in your PHP program without regard to variable scope.

PHP constants are case-sensitive.

To define a constant, use the define() function:

define( "MY_CONSTANT", "19" ); // MY_CONSTANT always has the string value  " 19 "
echo MY_CONSTANT;     // Displays  " 19 "  (a string, not an integer)

Demo

<?php
    $radius = 4;/*from   ww  w.  ja v a 2 s  .c o m*/
    
    $diameter = $radius * 2;
    $circumference = M_PI * $diameter;
    $area = M_PI * pow( $radius, 2 );
    
    echo "A radius of " . $radius . " \n ";
    echo "A diameter of " . $diameter . " \n ";
    echo "A circumference of " . $circumference . " \n ";
    echo "An area of " . $area . " \n ";

?>

Result

Here, the script stores the radius of the circle to test in a $radius variable.

Then it calculates the diameter and stores it in a $diameter variable.

Next it works out the circle's circumference, which is pi times the diameter, and stores the result in a $circumference variable.

It uses the built-in PHP constant, M_PI , which stores the value of pi.