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];
}
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.