测试文件是否在包含路径中的任何位置 [英] Test whether a file exists anywhere in the include path

查看:86
本文介绍了测试文件是否在包含路径中的任何位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个自动加载功能,并且在其内部逻辑中,我想在包含该文件之前先测试路径中是否存在某个文件.

I'm writing an autoload function and in the inner logic of it would like to test whether a certain file exists somewhere in the path prior to including it.

这是逻辑:

如果包含路径中的任意位置中存在名为$className'.specialversion.php'的文件,则将其包含在内.否则,让其他自动加载器负责为此类添加文件.

If a file named $className'.specialversion.php' exists anywhere in the include path include it. Otherwise, let other autoloaders take care of including a file for this class.

此刻我只做:@include($calculatedPath);

我不确定是否是包含和抑制该错误的好方法.我宁愿在包含文件之前检查文件是否存在(包含路径中的某个位置).

I'm not sure if it's a good approach to include and suppress the error. I would rather check if the file exists (somewhere in the include path) prior to including it.

我的问题是:

  • 我可以在包含路径中的任何位置测试文件是否存在吗?
  • @include($calculatedPath);真的有问题吗?
  • Can I test for existence of a file anywhere in the include path?
  • Is it really problematic to do @include($calculatedPath);?

修改

一个重要的重音符号:我不知道文件应该在哪里.我只想知道它是否包含在包含路径中的目录之一中.所以我不能只做file_exists()之类的事情.

An important accent: I don't know where the file should be. I just want to know whether it exists in one of the directories in the include path. So I can't just do file_exists() or something like that.

推荐答案

从PHP 5.3.2开始,可以选择使用 stream_resolve_include_path() 函数的目的是

As of PHP 5.3.2 there is the option to use the stream_resolve_include_path() function whose purpose is to

根据与fopen()/include()相同的规则,针对[include]路径解析[a]文件名.

Resolve [a] filename against the include path according to the same rules as fopen()/include() does.

如果文件位于包含路径之一上,则将返回该路径(包括文件名).否则(即文件不在任何包含路径上),它将返回FALSE.

If the file exists on one of the include paths, then that path (including the file name) will be returned. Otherwise (i.e. the file was not on any of the include paths) it will return FALSE.

与此相关的您的自动装带器可能类似于:

Relating this to your needs, your autoloader might look something like:

function my_autoloader($classname) {
    $found = stream_resolve_include_path($classname . '.specialversion.php');
    if ($found !== FALSE) {
        include $found;
    }
}

这篇关于测试文件是否在包含路径中的任何位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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