出于性能原因,我们应该只使用 realpath()而不是 realpath() + file_exists()在检查文件或目录是否存在时 ??
案例 A::
if(realpath(__DIR__."/../file.php")===false)
案例 B::
if(file_exists(realpath(__DIR__."/../file.php"))===false)
我认为 CASE A
完成了工作,而 CASE B
完成了两次工作。
最佳答案
不仅情况 B 是多余的(因为根据 docs ,如果路径无法解析或文件不存在,则 realpath 返回 false),如果文件不存在,那就有点傻了。
由于此语句将返回 FALSE
:
realpath(__DIR__."/../file.php");
这个:
file_exists(realpath(__DIR__."/../file.php"));
真的是这样吗:
file_exists(FALSE); //!
作为旁注:
realpath
永远不会返回“FALSY”值。我的意思是它永远不会返回 == FALSE
但不会返回 === FALSE
的内容(例如 NULL
、 ''
, 0, array()).为什么?好吧,真正的路径将始终包含对根目录的引用 — *nix 系统(Mac、Unix、Linux)中的 /
和 Windows 中的 C:\
,以及这两个当用作 bool 值时(比如在 if、while 或 for 循环中),字符串将评估为 true。这意味着你可以这样做:
if(!realpath(__DIR__."/../file.php")) // do something
或者,如果您确实需要真实路径,您可以:
if(!($path = realpath(__DIR__."/../file.php")))
// file does not exist
else
// $path is now the full path to the file
关于php,realpath 与 realpath + file_exists 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8373859/