In the PHP constants section, we covered how to define and utilize constants in PHP scripts.
PHP also provides a special set of predefined constants known as magic constants. These constants vary based on where they are used in the script. For instance, the value of __LINE__
depends on the line number where it is referenced in your script.
Magic constants are identified by starting and ending with two underscores. Below, we'll explore some of the most useful magical PHP constants.
The __LINE__
constant retrieves the current line number within the file, as demonstrated below:
<?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
?>
The __FILE__
constant provides the full path and filename of the PHP script being executed. When used within an include statement, it returns the name of the included file.
<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>
The __DIR__
constant returns the directory path of the current PHP file. When used within an include statement, it returns the directory path of the included file. Here’s an example:
<?php
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
The __FUNCTION__
constant provides the name of the current function where it is used.
<?php
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
?>
The __CLASS__
constant retrieves the name of the current class. Below is an example:
<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
?>
The __METHOD__
constant provides the name of the current method within a class.
<?php
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
?>
The __NAMESPACE__
constant gives the name of the current namespace in PHP.
<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
?>