我这里有一个奇怪的问题
我正在尝试复制文件到文件夹
if ($folder) {
codes.....
} else if (!copy($filename, $root.$file['dest']) && !copy($Image, $root.$imagePath)){
throw new Exception('Unable to copy file');
}
我的问题是$image
文件从未被复制到目的地
但是,如果我这样做
if ($folder) {
codes.....
} else if (!copy($Image, $root.$imagePath)){
throw new Exception('Unable to copy file');
}
它的工作原理。
编辑:我知道第一个filename语句是真的
谁能帮我解决这个奇怪的问题?非常感谢!!这些都是优化的一部分。
由于&&
只有在两个条件都为真时才为真,因此计算(即执行)
copy($Image, $root.$imagePath)
时!copy($filename, $root.$file['dest'])
已返回false。
结果:如果第一次复制成功,第二次复制将不会执行,因为!copy(…)
将被评估为false。
建议:
// Perform the first copy
$copy1 = copy($filename, $root.$file['dest']);
// Perform the second copy (conditionally… or not)
$copy2 = false;
if ($copy1) {
$copy2 = copy($Image, $root.$imagePath);
}
// Throw an exception if BOTH copy operations failed
if ((!$copy1) && (!$copy2)){
throw new Exception('Unable to copy file');
}
// OR throw an exception if one or the other failed (you choose)
if ((!$copy1) || (!$copy2)){
throw new Exception('Unable to copy file');
}
你可能想说
else if (!copy($filename, $root.$file['dest']) || !copy($Image, $root.$imagePath))
(注:||
代替&&
)
实际上,一旦复制成功,&&
将永远不会为真,因此PHP将停止对表达式求值。
也就是说
$a = false;
$b = true;
if ($a && $b) {
// $b doesn't matter
}
如果!copy($filename, $root.$file['dest'])的计算结果为false,那么php就没有理由尝试对!copy($Image, $root.$imagePath)求值,因为整个xxx &&Yyy表达式将为false