Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php,realpath与realpath+;文件使用情况不存在_Php_Performance - Fatal编程技术网

php,realpath与realpath+;文件使用情况不存在

php,realpath与realpath+;文件使用情况不存在,php,performance,Php,Performance,出于性能原因,在检查文件或目录是否存在时,应仅使用而不是+ 案例A:: if(realpath(__DIR__."/../file.php")===false) 案例B:: if(file_exists(realpath(__DIR__."/../file.php"))===false) 我认为案例A做这项工作,案例B做这项工作两次。这是正确的。如果文件不存在,realpath()将返回false。案例B是多余的 不仅案例B是冗余的(因为如果路径无法解析或文件不存在,realpath会返回f

出于性能原因,在检查文件或目录是否存在时,应仅使用而不是+

案例A::

if(realpath(__DIR__."/../file.php")===false)
案例B::

if(file_exists(realpath(__DIR__."/../file.php"))===false)
我认为案例A做这项工作,案例B做这项工作两次。

这是正确的。如果文件不存在,realpath()将返回false。案例B是多余的


不仅案例B是冗余的(因为如果路径无法解析或文件不存在,realpath会返回false),如果文件不存在,这有点愚蠢

由于此语句将返回
FALSE

这:

这真的是:


请注意:
realpath
永远不会返回“FALSY”值。我的意思是,它永远不会返回
==FALSE
,但不会
==FALSE
(例如
NULL
'
,0,array()。为什么?好的,在*nix系统(Mac、Unix、Linux)和Windows系统中,实际路径总是包含对根的引用-
/
,这两个字符串在用作布尔值时(比如在if、while或for循环中),将计算为true。这意味着您可以:

if(!realpath(__DIR__."/../file.php")) // do something
或者,如果您需要实际拥有realpath,您可以:

if(!($path = realpath(__DIR__."/../file.php")))
   // file does not exist
else
   // $path is now the full path to the file

它们几乎一样,但不完全一样

案例A将检查路径是否存在,
realpath
将返回非假值,前提是扩展后的路径将指向文件或文件夹。此外,如果您传递
realpath
a
null
-值或空字符串,它将返回当前文件夹

案例B还可以检查返回的路径是否为常规文件(与目录相反!)。如果realpath解析文件夹的路径,则
is_file
调用将返回
false
,您可以从那里处理它

因此,
realpath
将检查给定路径中是否有文件或文件夹(或其符号链接),并将空值扩展到当前目录。额外的
is_file
检查可以确保您使用的是文件而不是文件夹

用例B(使用
is_file
而不是
file_exists
)如果要确保使用的是文件,如果文件夹也正常,则使用用例a.:)


file\u exists
(与
is\u file
相反)也会为目录返回
true

很好的附加信息,我不知道使用空值或空字符串时的realpath行为,谢谢!!
file_exists(FALSE); //!
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