我有这个功能:
function formatSizeUnits($bytes,array $options = array()){
$forceFormat = isset($options["forceFormat"]) ? $options["forceFormat"] : false;
$suffix = !isset($options["suffix"]) || $options["suffix"] === true ? true : false;
switch($bytes):
case $forceFormat === "gb":
case $bytes >= 1073741824 && $forceFormat === false:
$bytes = number_format($bytes / 1073741824, 2) . ($suffix === true ? " GB" : "");
break;
case $forceFormat === "mb":
case $bytes >= 1048576 && $forceFormat === false:
$bytes = number_format($bytes / 1048576, 2) . ($suffix === true ? " MB" : "");
break;
case $forceFormat === "kb":
case $bytes >= 1024 && $forceFormat === false:
$bytes = number_format($bytes / 1024, 2) . ($suffix === true ? " KB" : "");
break;
case $forceFormat === "b":
case $bytes > 1 && $forceFormat === false:
$bytes = $bytes . ($suffix === true ? " bytes" : "");
break;
case $bytes == 1 && $forceFormat === false:
$bytes = $bytes . ($suffix === true ? " byte" : "");
break;
default:
$bytes = "0".($suffix === true ? " bytes" : "");
endswitch;
return $bytes;
}
当我像这样运行时:
formatSizeUnits(0);
它返回:
0.00 GB
$forceFormat
为false
,$suffix
为true
。
我不明白为什么它会在GB
中返回。我希望它只返回0 bytes
。
当我在第一个switch语句(var_dump
之一)中放入gb
时,它会这样说:
case $forceFormat === "gb":
case $bytes >= 1073741824 && $forceFormat === false:
var_dump($bytes >= 1073741824, $forceFormat);
结果:
(bool(false)
bool(false)
我想知道为什么$bytes >= 1073741824
和$forceFormat
都可能是假的,它仍会运行。
我该如何解决这个问题?
答案 0 :(得分:0)
当$bytes
为0
时,表达式$bytes >= 1073741824 && $forceFormat === false
的评估结果为false
。 switch
语句跳转到表达式与case
匹配的第一个$bytes
。以下脚本演示了false
匹配0
。
<?php
switch (0) {
case false:
echo '0 is false';
break;
case true:
echo '0 is true';
break;
default:
echo '0 is something else';
break;
}
?>
因为您想跳转到case
true
,您应该使用switch (true)
。