根据性能原因,在检查文件或目录的存在时,我们应该只使用realpath()而不是realpath() + file_exists()?
案例A ::
if(realpath(__DIR__."/../file.php")===false)
Run Code Online (Sandbox Code Playgroud)
案例B ::
if(file_exists(realpath(__DIR__."/../file.php"))===false)
Run Code Online (Sandbox Code Playgroud)
我认为CASE A做好工作,并CASE B做两次工作.
案例B不仅冗余(如果路径无法解析,或者文件根据文档不存在,则realpath返回false ),如果文件不存在,那有点傻.
由于此声明将返回FALSE:
realpath(__DIR__."/../file.php");
Run Code Online (Sandbox Code Playgroud)
这个:
file_exists(realpath(__DIR__."/../file.php"));
Run Code Online (Sandbox Code Playgroud)
真的是这样的:
file_exists(FALSE); //!
Run Code Online (Sandbox Code Playgroud)
realpath永远不会返回"FALSY"值.我的意思是,它绝不会返回一些东西,== FALSE但不=== FALSE(例如NULL,''0,阵列()).为什么?好吧,真正的路径将始终包含对root- /in*nix系统(Mac,Unix,Linux)和C:\Windows中的引用,当用作布尔值时,这两个字符串将评估为true(例如,在if,while中,或循环).这意味着你可以这样做:
if(!realpath(__DIR__."/../file.php")) // do something
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要实际拥有 realpath,您可以:
if(!($path = realpath(__DIR__."/../file.php")))
// file does not exist
else
// $path is now the full path to the file
Run Code Online (Sandbox Code Playgroud)