$_REQUEST没有索引


$_REQUEST does not have index

我将querystring与$_REQUEST数组一起使用,每次我想访问任何密钥时,我都会使用此条件

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

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

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

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

使用isset:

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

$scene_id = isset($_REQUEST['scene_id']) ? $_REQUEST['scene_id'] : null;

在测试默认值之前,您可以用默认值预填充$_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
}

最首选的方法是使用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();
}
?>