SLIM Optional Parameter Issue

╄→гoц情女王★ 提交于 2019-12-25 05:26:17

问题


I trying to achieve something like this in Slim PHP:

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/>";
    });

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?


回答1:


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.

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.

Try this instead:

$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/>";
});

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



来源:https://stackoverflow.com/questions/18550041/slim-optional-parameter-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!