Magic constants are distinguished by their
There are currently eight magical constants that change depending on where they are used. For example, the value of
__LINE__depends on the line that it's used on in your script.
These special constants are case-insensitive and are as follows:
|The current line number of the file.|
|The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.|
|The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to |
|The current function name|
|The class name. The class name includes the namespace it was declared in (e.g. |
|The trait name. The trait name includes the namespace it was declared in (e.g. |
|The class method name.|
|The name of the current namespace.|
Most common use case for these constants is debugging and logging
Difference between __CLASS__, get_class() and get_called_class()
__CLASS__ magic constant returns the same result as
get_class() function called without parameters and they both return the name of the class where it was defined (i.e. where you wrote the function call/constant name ).
get_called_class() functions call, will both return the name of the actual class which was instantiated:
Difference between __FUNCTION__ and __METHOD__
__FUNCTION__ returns only the name of the function whereas
__METHOD__ returns the name of the class along with the name of the function:
File & Directory Constants
You can get the name of the current PHP file (with the absolute path) using the
__FILE__ magic constant. This is most often used as a logging/debugging technique.
To get the absolute path to the directory where the current file is located use the
__DIR__ magic constant.
To get the absolute path to the directory where the current file is located, use
Getting current directory is often used by PHP frameworks to set a base directory:
Windows system perfectly understands the
/in paths so the
DIRECTORY_SEPARATORis used mainly when parsing paths.
Besides magic constants PHP also adds some fixed constants for working with paths:
DIRECTORY_SEPARATORconstant for separating directories in a path. Takes value
/on *nix, and
\on Windows. The example with views can be rewritten with:
- Rarely used
PATH_SEPARATORconstant for separating paths in the
$PATHenvironment variable. It is