How to make quick judgement and assignment without isset()?

前端 未结 4 434
面向向阳花
面向向阳花 2021-01-16 20:51

I am tired of using code like:

$blog = isset($_GET[\'blog\']) ? $_GET[\'blog\'] : \'default\';

but I can\'t use:

$blog = $_         


        
4条回答
  •  無奈伤痛
    2021-01-16 21:27

    You can just write a custom helper:

    function get($name, $default=null){
        return isset($_GET[$name]) ? $_GET[$name] : $default;
    }
    
    $blog = get('blog', 'default');
    

    Alternatively, you have the filter extension, e.g.:

    $blog = filter_input(INPUT_GET, 'blog') ?: 'default';
    

    It's not noticeably shorter but allows further validation and sanitisation (and it's also trivial to wrap in a custom function).

提交回复
热议问题