PHP - Constants

A constant like variable,is a temporary placeholder in memory that holds a value.unlike variable the value of a constant never changes.for example PI(3.14) are examples of constants.

The name for constants have the same rules as variables except that they do not have the leading dollar sign.the define() function is used to declare the requires the name of the constant and the value that is required to be assigned to that constant.


The constants name is always in uppercase.string values must be enclosed in quotation marks.although they can be created anywhere in the script,it is considered good practice to put them at the beginning of the script.

PHP Magic Constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.the following list of magic constants.

Constant Name



The current line number of the file.


The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.


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.


The function name.


The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.


The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).


The class method name.


The name of the current namespace.

Example of Magic Constants

 namespace veewom;
 echo "Full Path and File Name : '" . __FILE__ . "'.\n";
 echo "File Path : '" . __DIR__ . "'.\n";
 echo "Line Number : " . __LINE__ . ".\n";
 function veewom() 
   echo "From :  '" . __FUNCTION__ . "' function.\n";
 class MagicConstants 
 public function printClassName() 
	echo "This is " . __CLASS__ . "Class.\n";
 public function printMethodName() 
	echo "This is " . __METHOD__ . "Method.\n";
 public function printFunction()
	echo "Function '" . __FUNCTION__ . "'Inside Class.\n";
 public function printNamespace() 
	echo "Namespace Name : '" . __NAMESPACE__ . "'.\n";
 $test_magic_constants = new MagicConstants;


Full Path and File Name : 'C:\wamp\www\New folder\index.php'.
File Path : 'C:\wamp\www\New folder'.
Line Number : 9.
From : 'veewom\veewom' function.
This is veewom\MagicConstantsClass.
This is veewom\MagicConstants::printMethodNameMethod.
Function 'printFunction'Inside Class.
Namespace Name : 'veewom'. 								
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!