Magic Constants in PHP

PHP has predefined constants that come with various extensions. Knowing these constants allows us to use PHP more effectively.

1.) __LINE__

Returns the line number where it is used.

echo "Line number is : ". __LINE__;

//OUTPUT: Line number is : 2

2.) __FILE__

Returns the file path and filename.

echo "File path : ". __FILE__;

//OUTPUT: File path : C:\Bitnami\wampstack-7.3.25-0\apache2\htdocs\learn-lara\app\Http\Controllers\FrontController.php

3.) __DIR__

Returns the directory where the file is located.

echo "Folder path : ". __FILE__;

//OUTPUT: Folder path : C:\Bitnami\wampstack-7.3.25-0\apache2\htdocs\learn-lara\app\Http\Controllers

4.) __FUNCTION__

When used inside a function, it returns the name of the function it is in.

public function myFunction()
    {
  		echo "Function name : ". __FUNCTION__;
	}

//OUTPUT: Function name : myFunction

5.) __CLASS__

When used inside a class, it returns the name of the class it is in. It is also used in traits.

class FooBar
{
    public function getClassName(){
        return __CLASS__;
    }
}
$obj = new FooBar();
echo $obj->getClassName();

//OUTPUT: FooBar

6.) __TRAIT__

When used inside a trait, it returns the name of the trait it is in.

trait FooBarTrait{  
    function myTraitFunction(){  
        echo __TRAIT__;  
        }  
    }  
    class Student{  
        use FooBarTrait;  
        }  
    $a = new Company;  
    $a->myTraitFunction(); 

//OUTPUT: FooBarTrait

7.) __METHOD__

Returns the name of the method in which it is used.

class Student
{
    public function myClassMethod(){
        return __METHOD__;
    }
}
$obj = new Student();
echo  $obj->myClassMethod();

//OUTPUT: myClassMethod

8.) __NAMESPACE__

Returns the current namespace.

namespace FooBarNamespace;
  
class Student {
    public function myMethod() {
        return __NAMESPACE__;
    }
}
  
$obj = new Company();
echo  $obj->myMethod(); 
  
//OUTPUT: FooBarNamespace

9.) ClassName::class

Returns the fully qualified class name in which it is used.

namespace FooBarNamespace;
class Student{ }
  
echo Geeks::class;

//OUTPUT: FooBarNamespace\Student

Good luck…