这是错误抑制运算符的不好实践吗? [英] Is this bad practice use of the error suppression operator?
问题描述
我正在数据库驱动的站点上工作,该站点正在使用常规数据库方法而不是准备好的语句.因此,当传递给表单操作PHP脚本时,我必须清理POST和GET变量.
I'm working on a database driven site which is using normal database methods rather than prepared statements. Because of this I have to sanitise POST and GET variables when passed to a form action PHP script.
定义了一个sanitise
方法,该方法试图尽可能地对用户输入进行清理,但是我尝试减少用于测试POST和GET变量是否存在的代码以及用于定义具有默认值的变量的代码(如果有的话)他们不存在.
There is a sanitise
method defined which attempts to sanitise the user input as best as possible but I am trying to cut down the code that tests for the POST and GET variable's existence and the code for defining variables with default values if they don't exist.
这是我想出的,但是它给我和其他开发人员留下了不良的印象,因为我们所有人都认为错误抑制运算符正在被滥用:
This is what I came up with but its leaving a bad taste in mine and other dev's mouth as we all feel that the error suppression operator is being abused:
$Page = sanitise(@$_GET["page"], "Unspecified");
$Timestamp = sanitise(@$_POST["time"], time());
请您给我一些有关此代码的评论吗?我不同意这是不理想的,但是它确实减少了很多代码,并且比我们拥有的代码更具可读性.
Please can you give me some critique of this code? It's not ideal I'll agree, but it does cut down on a lot of code and is a lot more readable than what we had.
我试图在一行中实现以下目标:
I tried to achieve the following in one line:
- 测试变量的存在.
- 如果存在,请清理输入并分配给变量.
- 如果不存在,请创建一个变量,但使用默认值.
您怎么看?
这是我在这里问的一种延续:
将未设置的变量传递给函数
This is sort of a continuation of what I was asking here:
Passing unset variables to functions
推荐答案
为自己节省一些编码,并使用几个静态函数创建一个"Input"类,如下所示:
Save yourself some coding and make an "Input" class with several static functions, like this:
class Input {
public static function get($key, $default = null)
{
return (array_key_exists($key, $_GET)) ? $_GET[$key] : $default;
}
// same thing for $_POST...
}
然后您可以像这样调用您的清理函数...
Then you could call your sanitize function like so...
sanitize(Input::get('page', 'Unspecified'));
这篇关于这是错误抑制运算符的不好实践吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!