多层次的条件判断如何用 when 来构造

if (A) {
    if (A1) {
    } elseif (A2) {
    }
} elseif (B) {
    if (B1) {
    } elseif (B2) {
    }
}

如何用when来构造这些条件?
(别说把条件按组合用&&拼到一个括号里去)

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
leo
最佳答案

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前
讨论数量: 10
leo

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前
leo

我从来不用 when,因为我很讨厌写闭包函数的 function

$builder = ModelClass::query()->where(shared conditions);
if (A) {
    if (A1) {
        $builder->where(special conditions 1);
    } elseif (A2) {
        $builder->where(special conditions 2);
    }
} elseif (B) {
    if (B1) {
        $builder->where(special conditions 3);
    } elseif (B2) {
        $builder->where(special conditions 4);
    }
}
5年前 评论
Rancy 3年前

@leo 可是不用when的话,那么每次构造查询,都得把完整查询再写一遍岂不是代码很重复?

5年前 评论
leo

@kiyoma 当然不是,参考我上面的代码(刚刚调整了一下更能说明清楚)

5年前 评论

@leo 不好意思,前面没注意看。学到了,谢谢。

5年前 评论

@leo +1 讨厌写一个又一个的 function,啥时候 PHP 有原生的 Lambda 支持就好了... 想念 C# 的一堆语法糖。

5年前 评论

@leo 老师跳槽到了RightCapital了吗?

5年前 评论
leo

@Flourishing 是的

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!