SLIM 可选参数问题 [英] SLIM Optional Parameter Issue

查看:54
本文介绍了SLIM 可选参数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Slim PHP 中实现这样的目标:

I trying to achieve something like this in Slim PHP:

页面/p1/p2/p3/p4

page/p1/p2/p3/p4

我想要如果我从右边(显然)遗漏了参数,那么我想根据我收到的任何参数来做我的事情.

I want that If I leave out params from the right(obviously) then I want to do my stuff based on whatever params I've received.

    $app->get('/page(/)(:p1/?)(:p2/?)(:p3/?)(:p4/?)', 
        function ($p1 = null, $p2 = null, $p3 = null, $p4 = null) {
            print empty($p1)? : '' . "p1: $p1/<br/>";
            print empty($p2)? : '' . "p2: $p2/<br/>";
            print empty($p3)? : '' . "p3: $p3/<br/>";
            print empty($p4)? : '' . "id: $p4<br/>";
    });

一切都按预期工作,但问题是每当我从末尾删除一个参数时,它会为我删除的每个参数打印 1 .为什么这样做?我在这里做错了什么?

Everything works as expected but the problem is whenever i remove a param from the end, it prints 1 for every param I remove. why is it doing so? what am I doing wrong here?

推荐答案

由于你省略了三元的第二部分(如果测试语句返回 true 应该打印什么),三元语句返回什么测试表达式的计算结果为.然后将结果打印出来.

Since you omitted the second part of the ternary (what should print if the test statement returns true), the ternary statement returns what the test expression evaluates to. That result is then printed out.

当你省略路由中的最后一个参数时,测试表达式结果为true,但由于你没有定义在这种情况下做什么,返回true并且 1 被打印出来.

When you omit the last parameter in the route, the test expression results to true, but since you do not define what to do in this case, true is returned and 1 is printed out.

试试这个:

$app->get('/page(/)(:p1/?)(:p2/?)(:p3/?)(:p4/?)', 
    function ($p1 = null, $p2 = null, $p3 = null, $p4 = null) {
        print empty($p1)? "" : '' . "p1: $p1/<br/>";
        print empty($p2)? "" : '' . "p2: $p2/<br/>";
        print empty($p3)? "" : '' . "p3: $p3/<br/>";
        print empty($p4)? "" : '' . "id: $p4<br/>";
});

现在脚本知道如果那些 empty() 表达式之一返回 true - 打印一个空字符串该怎么办.

Now the script knows what to do should one of those empty() expressions return true -- print an empty string.

这篇关于SLIM 可选参数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆