PHP Constants

In this chapter you will learn:

  1. What is a constant and why it is useful
  2. Syntax to define a constant
  3. Note for PHP constant
  4. Example - Create a constant
  5. Example - Create a constant case-insensitive
  6. Example - is constant defined
  7. Example - constant function to get constant value
  8. Example - use Math constant to calculate circle area

Description

Constants are used to make sure a value does not change throughout the running of the script.

Syntax

To define a constant, use the define() function, and include name of the constant, followed by the value for the constant, as shown here:

define( "MY_CONSTANT", "1" ); // MY_CONSTANT always has the string value "1"

Note

  • Constants may only contain scalar values such as Boolean, integer, float, and string (not values such as arrays and objects).
  • Constants can be used from anywhere in your PHP program without regard to variable scope.
  • Constants are case-sensitive.

Example 1


<?PHP
  define("aValue", 8); 
  print aValue; 
?>

The code above generates the following result.

Example 2

Pass in true as a third parameter to define() makes the constant case-insensitive:


<?PHP//from j a  v  a  2  s  . com
define("SecondsPerDay", 86400, true); 
print SecondsPerDay; 
print SECONDSperDAY; 
?>

The code above generates the following result.

Example 3

The defined() function is basically the constant equivalent of isset(), as it returns true if the constant string you pass to it has been defined.

For example:


<?PHP/* java2  s .c o  m*/
define("SecondsPerDay", 86400, true); 
if (defined("Secondsperday")) { 
    // etc 
} 
?>

Example 4

constant() returns the value of a constant.


<?PHP//from  j a  va  2  s.  co m
define("SecondsPerDay", 86400, true); 
$somevar = "Secondsperday"; 
print constant($somevar); 
?>

The code above generates the following result.

Example 5

Use Math constant to calculate circle area


<?php //from  j a  va 2  s . c  o m
         $radius = 4; 

         $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 "; 
               
?>  

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is a string
  2. Syntax to define string in PHP
  3. Example - Create a string in PHP
  4. Multline strings
Home » PHP Tutorial » PHP Data Types
PHP Data Types
PHP Boolean
PHP Integer
PHP Float
PHP Data Type Cast
PHP Automatic Type Conversion
PHP Super globals
PHP References
PHP Constants