Constants are similar to variables, holding information to be accessed later, except that they are what they sound like—constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered. One example of a use for a constant is to hold the location of your server root (the folder with the main files of your website). You would define such a constant like this:
PHP comes ready-made with dozens of predefined constants that you generally will be unlikely to use as a beginner to PHP.However there are few known as magic constants.The names of the magic constants always have two underscore at the beginning anf two at the end,so that we wont try accidentally try to name one of our own constants with a name that has declared and used already.
The following are some of the magic constant used in PHP:
The current line number of the file.
The full path and filename of the file. If used inside an include, the name of the included file is returned. In PHP 4.0.2, __FILE__ always contains an absolute path with symbolic links resolved, whereas in older versions it might contain a relative path under some circumstances.
The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ The function name. (Added in PHP 4.3.0.) As of PHP 5, returns the function name as it was declared (case-sensitive). In PHP 4, its value is always lowercase.
__CLASS__ The class name. (Added in PHP 4.3.0.) As of PHP 5, returns the class name as it was declared (casesensitive). In PHP 4, its value is always lowercased.
__METHOD__ The class method name. (Added in PHP 5.0.0.) The method name is returned as it was declared (casesensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined at compile time. (Added in PHP 5.3.0.)
CONSTANT IN PHP
define() function is used to set a constant
It takes three parameters they are: 1. Name of the constant 2. Value of the constant 3. Third parameter is optional. It specifies whether the constant name should be case-insensitive. Default is false
CONSTANT STRING EXAMPLE
<?php /* Here constant name is ‘Hai’ and ‘Hello Friend’ is its constant value and true indicates the constant value is caseinsensitive */
OUTPUT OF THE ABOVE GIVEN EXAMPLE IS AS FOLLOWS:
EXAMPLE FOR CONSTANT IN PHP
// case-sensitive constant name
define("GREETING", "Welcome to readexpert.com!");
PHP EXAMPLE TO CALCULATE THE AREA OF THE CIRCLE
<?php // defining constant value PI = 3.14
OUTPUT of the above given Example is as follows: