PHP - 可以在所需脚本中获取需求脚本的魔法常量 __FILE__ 吗?

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

是否可以在所需文件中获取需求脚本(需要另一个文件)的魔法常量__FILE__?

例如:

requirer.php

<?php

require 'pathtorequired/required.php';

required.php

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

注意:它们不在同一个文件夹中,问题是关于该功能的可能性,而无需在需求文件中创建常量。


关于@MarkusZeller 评论:

这个建议很好,但是在要求文件中使用绝对路径常量或使用相对路径之间进行选择,我更喜欢第一个选项。

来自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

所以就真正的 "magical" 常量而言,答案是否定的。

据我所知,在任何默认扩展中也没有常量(参见 https://www.php.net/manual/en/extensions.membership.php#extensions.membership.core

也许有提供此功能的第三方扩展,但我从未听说过,因此您可能无法在要求文件中设置常量,或者自己编写一个扩展。