Advertisement

Google Ad Slot: content-top

PHP Magic Constants

~1 min read · PHP
On this page

Magic constants are predefined constants that change based on their location in the code. Unlike regular constants, they do not have fixed values; instead, their values change depending on where they are used. Magic constants start and end with double underscores (__), except for the ClassName::class constant.


Summary of PHP Magic Constants

Magic Constant

Description

Current line number

Full path and filename of the file

Directory of the file

Function name

Class method name

Current namespace

Trait name (PHP 5.4+)

Returns the name of the specified class and the name of the namespace, if any.

1. __LINE__


  • Represents the current line number in the script.
Example
Try it yourself

2. __FILE__


  • Represents the full path and filename of the file.
  • Useful for finding the script's exact location.
Example
Try it yourself

3. __DIR__


  • Represents the directory of the file.
Example
Try it yourself

4. __FUNCTION__


  • Represents the function name (case-sensitive) where it is used.
  • If used outside a function, it will return an empty string.
Example
Try it yourself

5. __CLASS__


  • Represents the class name (case-sensitive) where it is used.
  • If used outside a class, it returns an empty string.
  • From PHP 5.4 onward, __CLASS__ includes the namespace in its value (if applicable).
Example
getClassName(); ?>
Try it yourself

6. __METHOD__


  • Represents the class method name where it is used.
  • Combines the class name and the method name.
Example
myMethod(); ?>
Try it yourself

7. __NAMESPACE__


  • Represents the name of the current namespace.
  • If used outside of any namespace, it returns an empty string.
Example
Try it yourself

8. __TRAIT__ (Introduced in PHP 5.4)


  • Represents the trait name where it is used.
  • Useful for traits to refer to themselves.
Example
getTraitName(); ?>
Try it yourself

9. ClassName::class


  • Returns the name of the specified class and the name of the namespace, if any.
Example
myValue(); ?>
Try it yourself