检查是否包含或加载文件 [英] Check if a file was included or loaded

查看:68
本文介绍了检查是否包含或加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何优雅的方法通过使用include/include_once/require/require_once来检查是否包含文件,或者页面是否实际上是直接加载的?创建类时,我正在尝试在类文件中设置测试文件.

Is there any elegant way to check if a file was included by using include/include_once/require/require_once or if the page was actually loaded directly? I'm trying to set up a testing file inside class files while I'm creating them.

我正在寻找类似于Python的if __name__ == "__main__":技术的东西.无需设置全局变量或常量.

I'm looking for something similar to Python's if __name__ == "__main__": technique. Without setting globals or constants.

推荐答案

引用自:

我一直在寻找一种方法来确定文件中是否包含或直接调用了文件.在我执行任务的某个时刻,我通过了该线程.从PHP手册中检查了此站点以及其他站点和页面上的各种其他线程,我很高兴并提出了以下代码:

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牛仔

Credit: @Interwebs Cowboy

这篇关于检查是否包含或加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆