有没有什么优雅的方法可以使用 include
来检查文件是否包含在内?/include_once
/require
/require_once
或者如果页面实际上是直接加载的?我在创建类文件时尝试在类文件中设置测试文件。
我正在寻找类似于 Python 的 if __name__ == "__main__":
的东西技术。无需设置全局变量或常量。
最佳答案
引自:How to know if php script is called via require_once()?
I was looking for a way to determine if a file have been included or called directly, all from within the file. At some point in my quest I passed through this thread. Checking various other threads on this and other sites and pages from the PHP manual I got enlightened and came up with this piece of code:
if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) {
echo "called directly";
} else {
echo "included/required";
}
In essence it compares if the name of the current file (the one that could be included) is the same as the file that is beeing executed.
图片来源:@Interwebs Cowboy
关于php - 检查文件是否被包含或加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999658/