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.

There are eight magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and these constants are called Magic constants and are as follows:

__LINE__   The current line number of the file.

__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.

__DIR__   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.

__FUNCTION__   The function name.

__CLASS__   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.

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

__METHOD__   The class method name.

__NAMESPACE__   The name of the current namespace.

Sample code

The following PHP code will demonstrate the use of each magic constant.

 namespace TestProject;
 echo "This file full path and file name is " . __FILE__ . ".\n";
 echo "<br>";
 echo "This file full path is " . __DIR__ . ".\n";
 echo "<br>";
 echo "This is line number " . __LINE__ . ".\n";
 echo "<br>";
 function test_function_magic_constant() {
 echo "This is from " . __FUNCTION__ . " function.\n";
 echo "<br>";
 // Really simple class for testing magic constants
 class TestMagicConstants {
 public function printClassName() {
 echo "This is " . __CLASS__ . " class.\n";
 echo "<br>";
 public function printMethodName() {
 echo "This is " . __METHOD__ . " method.\n";
 echo "<br>";
 public function printFunction() {
 echo "This is function " . __FUNCTION__ . " inside class.\n";
 echo "<br>";

 public function printNamespace() {
 echo "Namespace name is " . __NAMESPACE__ . ".\n";
 $test_magic_constants = new TestMagicConstants;