我在PHP中有一个简单的wee清理函数
它接受一个值或值的数组,并进行一些输入清理。现在我使用mysqli,它将行作为对象获取,因此我需要能够将它应用于obejct以及数组
function filter_out($output=''){
if($output != ''){
// i.e passed $_POST array
if(is_array($output)){
$newoutput = array();
foreach($output as $outputname=>$outputval){
$newoutput[$outputname] = stripslashes($outputval);
$newoutput[$outputname] = htmlspecialchars($newoutput[$outputname]);
}
} else if(is_object($input)){
?
}
}
}谁能告诉我怎样才能用对象作为输入来做同样的事情呢?
发布于 2010-12-11 02:03:22
您要查找的函数是get_object_vars
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
///...
}不要试图迭代对象本身(foreach ($object as $key => $value)),因为它并不总是正确工作的。有时它会(以stdClass为例),有时不会(任何实现Traversable的类...
编辑
就你的评论而言...只要这些类没有做任何有趣的事情(__get或__set,protected或private),您可以这样做:
$newoutput = clone $input; //make a copy to return
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}但我真的想不出有什么方法能百分之百有效……另一种选择是返回一个nieve对象(stdclass),而不是提交的对象:
$newoutput = new StdClass();
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}发布于 2010-12-11 02:24:27
回答操作员对ircmaxell's answer的评论
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$input->$outputname = htmlspecialchars(stripslashes($outputval));
}发布于 2010-12-11 02:35:37
既然您提到了来自mysqli的数组和对象,我猜它们就是stdClass,那么为什么不直接将对象转换为数组呢?
$newoutput = array()
foreach ((array) $output as $key => $value) {
$newoutput[$key] = htmlspecialchars(stripslashes($value));
}或者你也可以就地完成:
$output = (array) $output;
foreach ($output as &$value) {
$value = htmlspecialchars(stripslashes($value));
}因此,单个流可能如下所示:
function filter_out($output=''){
if($output != ''){
// i.e passed $_POST array
$is_array = is_array($output);
$output = (array) $output;
foreach($output as &$outputval){
$outputval = htmlspecialchars(stripslashes($outputval));
}
if (!$is_array) {
$output = (object) $output;
}
}
return $output;
}https://stackoverflow.com/questions/4411849
复制相似问题