使用php如何減少if else 的多重嵌套判斷語句

使用php減少if else 的多重嵌套判斷語句

在平時的代碼中,爲了代碼的高質量和可讀性,建議使用if-return代替if-else的結構,既符合單一出口的原則,又實現了代碼的嵌套邏輯向平行邏輯轉換,應該具備這種設計思想!

優化代碼

if層次越少越好

function getThumbQrcodeSize($material_pic_height)
    {
        $thumb_qrcode_size = 150;
        //如果高度小於2000,則生成280*280的二維碼
        if ($material_pic_height < 1000) {
            return $thumb_qrcode_size = 150;
        }

        if ($material_pic_height >= 1000 && $material_pic_height < 2000) {
            return $thumb_qrcode_size = 280;
        }
        //如果高度大於等於2000,小於4000px 則生成480*480的二維碼
        if ($material_pic_height >= 2000 && $material_pic_height < 4000) {
            return $thumb_qrcode_size = 480;
        }

        //如果高度大於等於4000,小於6000px 則生成580*580的的二維碼
        if ($material_pic_height >= 4000 && $material_pic_height < 6000) {
            return $thumb_qrcode_size = 580;
        }

        //如果高度大於等於6000,小於10000px  則生成280*280的二維碼
        if ($material_pic_height >= 6000 && $material_pic_height < 10000) {
            return $thumb_qrcode_size = 680;
        }

        //如果高度大於等於10000,則生成960*960的二維碼
        if ($material_pic_height >= 10000) {
            return $thumb_qrcode_size = 960;
        }
        //都沒有匹配上,則返回默認的
        return $thumb_qrcode_size;
    }
$material_pic_height=1000;
getThumbQrcodeSize();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章