PHP Magic Constants. With Examples
Posted by TotalDC
In the PHP constants chapter we’ve learned how to define and use constants in PHP. And now let’s dive deeper and take a look at PHP magic constants.
What Is Magic Constants
PHP gives you predefined constants that change depending on where they are used. These constants are called magic constants. Magic constants begins and ends with two underscores.
__LINE__
This __LINE__ constant returns the line count of the file. For example:
<?php
print "Line number " . __LINE__ . "<br>"; // Result: 2
print "Line number " . __LINE__ . "<br>"; // Result: 3
print "Line number " . __LINE__ . "<br>"; // Result: 4
?>
__FILE__
__FILE__ constant returns full path and name of the PHP file. Just like this:
<?php
// Displays full path of this file
print "Full path of this file is: " . __FILE__;
?>
__DIR__
This constant returns directory of the file. If you use this constant inside included file, then directory of the included file is returned. Let’s look at the example:
<?php
// Displays the directory of this file
print "The directory of this file is: " . __DIR__;
?>
__FUNCTION__
__FUNCTION__ returns the name of the current function.
<?php
function myFunction(){
print "Name of the function is - " . __FUNCTION__;
}
myFunction(); // Result: Name of the function is - myFunction
?>
__METHOD__
__METHOD__ constant returns name of the current method:
<?php
class Sample
{
public function myMethod(){
print __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Result: Sample::myMethod
?>
__CLASS__
This constant returns name of the current class. Here is an example:
<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
print $obj->getClassName(); // Result: MyClass
?>
__NAMESPACE__
This constant returns the name of the current namespace:
<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
print $obj->getNamespace(); // Result: MyNamespace
?>
Leave a Reply