PHP Magic Constants
In this tutorial you will learn how to work with PHP magic constants.
What is Magic Constants
In the PHP constants chapter we've learned how to define and use constants in PHP script.
PHP moreover also provide a set of special predefined constants that change depending on where they are used. These constants are called magic constants. For example, the value of __LINE__
depends on the line that it's used on in your script.
Magic constants begin with two underscores and end with two underscores. The following section describes some of the most useful magical PHP constants.
__LINE__
The __LINE__
constant returns the current line number of the file, like this:
Example
Run this code »<?php
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
?>
__FILE__
The __FILE__
constant returns full path and name of the PHP file that's being executed. If used inside an include, the name of the included file is returned.
Example
Download<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>
__DIR__
The __DIR__
constant returns the directory of the file. If used inside an include, the directory of the included file is returned. Here's an example:
Example
Download<?php
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
__FUNCTION__
The __FUNCTION__
constant returns the name of the current function.
Example
Run this code »<?php
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
?>
__CLASS__
The __CLASS__
constant returns the name of the current class. Here's an example:
Example
Run this code »<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
?>
__METHOD__
The __METHOD__
constant returns the name of the current class method.
Example
Run this code »<?php
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
?>
__NAMESPACE__
The __NAMESPACE__
constant returns the name of the current namespace.
Example
Download<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
?>