通过引用访问 GET 和 POST
我在 stackoverflow 上的另一个答案中学习了如何通过引用访问,但无法再次找到它。无论如何,以下方法不安全或根本不可靠吗?
protected function checkVar($requestType, $varname, $checkIfNumber = false)
{
switch($requestType)
{
case 'GET':
$sg = &$_GET;
break;
case 'POST':
$sg = &$_POST;
break;
default:
throw new Exception('Variable `$requestType` is not `GET` or `POST` in AController::checkVar().');
}
if(!isset($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is not set in AController::checkVar().");
} else if(empty($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is empty in AController::checkVar().");
} else if($checkIfNumber) {
if(!ctype_digit($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is not a number in AController::checkVar().");
}
}
return $sg[$varname];
}
I learned how to access by reference in another answer on stackoverflow, but cannot find it again. Anyways, is the following method unsafe or at all unreliable?
protected function checkVar($requestType, $varname, $checkIfNumber = false)
{
switch($requestType)
{
case 'GET':
$sg = &$_GET;
break;
case 'POST':
$sg = &$_POST;
break;
default:
throw new Exception('Variable `$requestType` is not `GET` or `POST` in AController::checkVar().');
}
if(!isset($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is not set in AController::checkVar().");
} else if(empty($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is empty in AController::checkVar().");
} else if($checkIfNumber) {
if(!ctype_digit($sg[$varname])) {
throw new Exception("$requestType variable [$varname] is not a number in AController::checkVar().");
}
}
return $sg[$varname];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是您应该使用引用的方式。只要值不改变,“复制”操作实际上更便宜,并且这里不需要引用(特别是当您不是通过引用返回,而是实际制作副本时)。代码中这一点的引用唯一能做的就是稍后导致难以追踪的模糊错误。
This is not how you should use references. A 'copy' operation is actually cheaper as long as the values don't change, and there is no reference needed here (especially as you're not returning by reference, but actually making a copy). The only thing references in this point of the code can do is cause obscure errors later on which can be quite hard to track down.
这就是为什么我们有 $_REQUEST 超级全局。
我知道这不是严格意义上的同一件事,但恕我直言,它已经足够好了。
That's why we have the $_REQUEST superglobal.
I know it's not strictly the same thing, but IMHO it's good enough.