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

六月ゝ 毕业季﹏ 提交于 2019-12-01 13:18:25

问题


I am tired of using code like:

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

but I can't use:

$blog = $_GET['blog'] || 'default';

Is there any way to do this without using isset()?


回答1:


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;



回答2:


Write a helper function.

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

Usage:

$blog = arrayValue($_GET, 'blog');



回答3:


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.




回答4:


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).



来源:https://stackoverflow.com/questions/26477475/how-to-make-quick-judgement-and-assignment-without-isset

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