我的职能是:
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
。
当我在第一个开关语句( var_dump
)中放置一个gb
时,它会这样说:
case $forceFormat === "gb":
case $bytes >= 1073741824 && $forceFormat === false:
var_dump($bytes >= 1073741824, $forceFormat);
结果:
(bool(false)
bool(false)
我想知道为什么$bytes >= 1073741824
和$forceFormat
都可能是假的,而它仍然运行这种情况。我怎么才能解决这个问题?
发布于 2015-07-09 23:35:55
当$bytes
为0
时,表达式$bytes >= 1073741824 && $forceFormat === false
的计算结果为false
。switch
语句跳转到表达式与$bytes
匹配的第一个case
。下面的脚本演示了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)
。
https://stackoverflow.com/questions/31334394
复制