php - 检查文件是否被包含或加载

标签 php

有没有什么优雅的方法可以使用 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/

相关文章:

php - 如何在 PHP 中对文件进行数字签名

javascript - Ajax - 返回的 json 对象在 ie 中为空

php - 无法让 mysql_insert_id() 工作

php - 在 PhpStorm 中向上/向下移动方法

php - 使用 php 5.3 和 Laravel 4 取消引用数组

php - 我使用 mysql 命令没有从 ssh2_exec() 得到任何结果

php - 使用 php 循环从 mysql 数据数组动态生成 json 文件

PHP、SQL 插入无效

php - 我无法上传图片 php 一切正常,但上传失败

用于处理关联条目的 PHP/MySQL 代码