phprequiremagic-constants

PHP - It is possible to get the magic constant __FILE__ of the requirer script inside the required script?


It is possible to get the magic constant __FILE__ of a requirer script( the file that requires another ) inside the required file?

For example:

requirer.php

<?php

require 'pathtorequired/required.php';

required.php

<?php
echo __REQUIRER_FILE__; // => fullpathtorequirerfile/requirer.php

Note: they are not in same folder, the question is about the possibility of that feature without create a constant in requirer file.


About @MarkusZeller comment:

The suggestion is good, but choosing between have an absolute path constant in the requirer file or work with relative paths, i prefer the first option.


Solution

  • From the docs:

    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, which are resolved at runtime

    So in terms of truly "magical" constants, the answer is no.

    AFAIK, there also isn't a constant in any of the default extension (see https://www.php.net/manual/en/extensions.membership.php#extensions.membership.core)

    Perhaps there's a third party extension that provides this, but I never heard of one, so you may be stuck with setting the constant in the requirer file, or write an extension yourself.