Skip to main content

PHP Magic Constants

PHP has nine special predefined constants, known as "magic constants", and their value depends on where in your code you use them.

They tell a script about itself and its surroundings: which file and directory it is in, which line is running, the function or class it is inside, and so on.

You can recognize most of them by the double underscores (__) at both ends of the name. The one exception is ClassName::class.

Case doesn't matter, so __line__ gives the same result as __LINE__.

Here is what each one gives you:

  • __CLASS__ - the name of the class, when used inside one.
  • __DIR__ - the folder that holds the file.
  • __FILE__ - the file's name with its full path.
  • __FUNCTION__ - the name of the function, when used inside one.
  • __LINE__ - the line number it appears on.
  • __METHOD__ - in a function that belongs to a class, the class name and function name together.
  • __NAMESPACE__ - the name of the namespace, when used inside one.
  • __TRAIT__ - the name of the trait, when used inside one.
  • ClassName::class - the name of the given class, along with its namespace if it has one.