0

我正在使用带有$_REQUEST数组的查询字符串,每次我想访问任何键时,我都使用这个条件

if(array_key_exists('scene_id', $_REQUEST))

有什么方法可以直接使用$_REQUEST["scene_id"]而不会出现任何警告和错误?

4

4 回答 4

4

当然,您可以将其包装在您自己的函数中:

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

echo request('scene_id');
于 2012-09-12T13:37:03.740 回答
1

使用isset

if(isset($_REQUEST['scene_id']))

或者

$scene_id = isset($_REQUEST['scene_id']) ? $_REQUEST['scene_id'] : null;
于 2012-09-12T13:35:21.117 回答
0

最喜欢的方法是使用isset if(isset($_REQUEST['scene_id']))但您实际上可以使用@符号来抑制错误消息,但请注意该错误仍然存​​在并且需要正确处理它

来自 PHP 文档

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

示例 1

if(@$_REQUEST['scene_id'])
{
    echo "ok" ;
}

示例 2(过滤器、验证或异常)

try {
    if (!isset($_REQUEST['scene_id']))
        throw new Exception("Missing Scene ID");

    if (!filter_var($_REQUEST['scene_id'], FILTER_SANITIZE_NUMBER_INT))
        throw new Exception("Only Valid Number Allowed");

    echo "Output ", $_REQUEST['scene_id'];
} catch ( Exception $e ) {
    print $e->getMessage();
}

?>
于 2012-09-12T13:35:48.653 回答
0

您可以在测试之前使用默认值预填充 $_REQUEST:

$expected = array(
    'scene_id'=>false,
    'another_var'=>'foo',
);

foreach($exptected as $key=>$default) {

    if (!isset($_REQUEST[$key])) {
        $_REQUEST[$key] = $default;
    }

}

if ($_REQUEST['scene_id') {
    // do stuff
}
于 2012-09-12T13:38:45.300 回答