PHP Magic Constants
They are similar to other predefined constants but as they change their values with the context, they are called magic constants.
There are nine magic constants in PHP. In which eight magic constants start and end with double underscores (__).
- __LINE__
- __FILE__
- __DIR__
- __FUNCTION__
- __CLASS__
- __TRAIT__
- __METHOD__
- __NAMESPACE__
- ClassName::class
All of the constants are resolved at compile-time instead of run time, unlike the regular constant. Magic constants are case-insensitive.
Changelog
Version | Description |
---|---|
5.3.0 | Added __DIR__ and __NAMESPACE__ magic constant |
5.4.0 | Added __TRAIT__ magic constant |
5.5.0 | Added ::class magic constant |
1. __LINE__
It returns the current line number of the file, where this constant is used.
Example-
Output:
Example for __LINE__You are at line number 4
2. __FILE__:
This magic constant returns the full path of the executed file, where the file is stored. If it is used inside the include, the name of the included file is returned.
Example-
Output:
Example for __FILE__C:\xampp\htdocs\program\magic.php
3. __DIR__:
It returns the full directory path of the executed file. The path returned by this magic constant is equivalent to dirname(__FILE__). This magic constant does not have a trailing slash unless it is a root directory.
Example-
Output:
Example for __DIR__C:\xampp\htdocs\programC:\xampp\htdocs\program
4. __FUNCTION__:
This magic constant returns the function name, where this constant is used. It will return blank if it is used outside of any function.
Example-
Output:
Example for __FUNCTION__The function name is testHie
5. __CLASS__:
It returns the class name, where this magic constant is used. __CLASS__ constant also works in traits.
Example-
Output:
Example for __CLASS__JTPbase
6. __TRAIT__:
This magic constant returns the trait name, where it is used.
Example-
Output:
Example for __TRAIT__created_trait
7. __METHOD__:
It returns the name of the class method where this magic constant is included. The method name is returned the same as it was declared.
Example-
Output:
Example for __METHOD__method:: constructmethod:: meth_fun
8. __NAMESPACE__:
It returns the current namespace where it is used.
Example-
Output:
Example for __NAMESPACE__This line will print on calling namespace.
9. ClassName::class:
This magic constant does not start and end with the double underscore (__). It returns the fully qualified name of the ClassName. ClassName::class is added in PHP 5.5.0. It is useful with namespaced classes.
Example-
Output:
Example for ClassName::classonlinequizstock.in\onlinequizstock
Note: Remember namespace must be the very first statement or after any declare call in the script, otherwise it will generate a Fatal error.
0 Comments: