Magic constants

PHP provides a large number of predefined constants to any script
which it runs. Many of these constants, however, are created by
various extensions, and will only be present when those extensions
are available, either via dynamic loading or because they have
been compiled in.

There are nine 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. All these "magical" constants are resolved
at compile time, unlike regular constants thats resolved at runtime.
These special constants are case-insensitive and are as follows:

A few "magical" PHP constants

Name

Description

__LINE__

The current line number of the file.

__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.

__DIR__

The directory of the file. If used inside an include,
the directory of the included file is returned. This is equivalent
to dirname(__FILE__). This directory name
does not have a trailing slash unless it is the root directory.

__FUNCTION__

The function name.

__CLASS__

The class name. The class name includes the namespace
it was declared in (e.g. Foo\Bar).
Note that as of PHP 5.4 __CLASS__ works also in traits. When used
in a trait method, __CLASS__ is the name of the class the trait
is used in.

__TRAIT__

The trait name. The trait name includes the namespace
it was declared in (e.g. Foo\Bar).

Note a small inconsistency when using __CLASS__ and __METHOD__ in traits (stand php 7.0.4): While __CLASS__ is working as advertized and returns dynamically the name of the class the trait is being used in, __METHOD__ will actually prepend the trait name instead of the class name!

Just learned an interesting tidbit regarding __FILE__ and the newer __DIR__ with respect to code run from a network share: the constants will return the *share* path when executed from the context of the share.

A lot of notes here concern defining the __DIR__ magic constant for PHP versions not supporting the feature. Of course you can define this magic constant for PHP versions not yet having this constant, but it will defeat its purpose as soon as you are using the constant in an included file, which may be in a different directory then the file defining the __DIR__ constant. As such, the constant has lost its *magic*, and would be rather useless unless you assure yourself to have all of your includes in the same directory.

Concluding: eye catchup at gmail dot com's note regarding whether you can or cannot define magic constants is valid, but stating that defining __DIR__ is not useless, is not!

You cannot check if a magic constant is defined. This means there is no point in checking if __DIR__ is defined then defining it. `defined('__DIR__')` always returns false. Defining __DIR__ will silently fail in PHP 5.3+. This could cause compatibility issues if your script includes other scripts.