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

前端 未结 4 404
面向向阳花
面向向阳花 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:16

    No there is no shorter way than that. You can create a class that handles the $_POST and $_GET variables and just user it whenever you call the blog.

    Example:

    $blog = Input::put("blog");

    The input class will have a static method which will determine when input is either have a $_POST and $_GET or a null value.

    0 讨论(0)
  • 2021-01-16 21:19

    You have to wait for the next version of PHP to get the coalesce operator

    // Uses $_GET['user'] if it exists -- or 'nobody' if it doesn't
    $username = $_GET['user'] ?? 'nobody';
    
    // Loads some data from the model and falls back on a default value
    $model = Model::get($id) ?? $default_model;
    
    0 讨论(0)
  • 2021-01-16 21:22

    Write a helper function.

    function arrayValue($array, $key, $default = null)
    {
        return isset($array[$key]) ? $array[$key] : $default;
    }
    

    Usage:

    $blog = arrayValue($_GET, 'blog');
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题