What are Magic Constants in PHP ?

  • In PHP magic constants are the predefined constants which is used on the basis of their use.
  • Constants are created by various extensions and there are nine magic constants in the PHP and all of the constant resolved at the compile-time, not like the regular constant which is resolved at run time.
  • In this there are eight magic constants which start and end with double underscores (__), they are.
    • __line__
    • __file__
    • __dir__
    • __function__
    • __class__
    • __method__
    • __namespace__
    • __trait__

__line__

  • This type of magic constant returns the current line number of the file.
  • In our program file if we use this magic constant somewhere then this constant will display the line number during compile time.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20%20%20__line__” message=”” highlight=”” provider=”manual”/]

__file__

  • This type of magic constant return the full path of the executed file with the name of the file.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20%20%20__file__” message=”” highlight=”” provider=”manual”/]

__dir__

  • This type of magic constant returns the directory of the executed file.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20%20%20%20__dir__” message=”” highlight=”” provider=”manual”/]

__function__

  • This type of magic constant returns the name of the function where it is included.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20%20%20__function__” message=”” highlight=”” provider=”manual”/]

__class__

  • This type of magic constant returns the name of the class where it is included.

Syntax

[pastacode lang=”php” manual=”__class__” message=”” highlight=”” provider=”manual”/]

__method__

  • This type of magic constant returns the method name where it is included.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20__method__” message=”” highlight=”” provider=”manual”/]

__namespace__

This type of magic constant returns the current namespace where it is included.

Syntax

[pastacode lang=”php” manual=”%20%20%20%20%20%20%20__namespace__” message=”” highlight=”” provider=”manual”/]

__trait__

  • This type of magic constant returns the trait name where it is included.

Syntax

[pastacode lang=”php” manual=”%C2%A0%20__trait__” message=”” highlight=”” provider=”manual”/]

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like