再次出现另一个问题。
public function __construct() {
$_GET = $this->clean($_GET);
$_POST = $this->clean($_POST);
...
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
我不明白为什么$data[$this->clean($key)] = $this->clean($value);
正在调用自己的函数。这样做有什么意义?优点
感谢, 丹尼尔
答案 0 :(得分:6)
这是一种称为递归的技术。这个特殊的函数下降到结构中,直到它处理非常简单的数据并清理它。
鉴于此:
$arr = array (
'<foo' => array(
'bat' => 'OMGWTFBBQ!!><!?!'
),
'bar' => 'baz'
);
它会开始:
<foo
一个数组? (没有)
<foo
变为<foo
<foo
用作键<foo
数组的值? (是)
bat
保持不变(仍调用htmlspecialchars,但不会改变任何内容))'OMGWTFBBQ!!><!?!'
是否为数组(否)?
'OMGWTFBBQ!!><!?!'
已转换为'OMGWTFBBQ!!><!?!'
'OMGWTFBBQ!!><!?!'
用于bat的值。bar
按原样返回(如上面的蝙蝠)baz
按原样返回。你可以这样想到
$arr = array (
'<foo' => array(
'bat' => 'OMGWTFBBQ!!><!?!'
),
'bar' => 'baz'
);
///////////////////////////////////////////
array (
clean('<foo') => array(
'bat' => 'OMGWTFBBQ!!><!?!'
),
'bar' => 'baz'
);
///////////////////////////////////////////
array (
'<foo' => clean( array(
'bat' => 'OMGWTFBBQ!!><!?!'
)),
'bar' => 'baz'
);
///////////////////////////////////////////
array (
'<foo' => array(
clean( 'bat' ) => 'OMGWTFBBQ!!><!?!'
)),
'bar' => 'baz'
);
///////////////////////////////////////////
array (
'<foo' => array(
'bat' => clean( 'OMGWTFBBQ!!><!?!' )
)),
'bar' => 'baz'
);
///////////////////////////////////////////
array (
'<foo' => array(
'bat' => 'OMGWTFBBQ!!><!?!'
)),
clean( 'bar' ) => 'baz'
);
///////////////////////////////////////////
array (
'<foo' => array(
'bat' => 'OMGWTFBBQ!!><!?!'
)),
'bar' => clean( 'baz' )
);
///////////////////////////////////////////
return array (
'<foo' => array(
'bat' => 'OMGWTFBBQ!!><!?!'
)),
'bar' => 'baz'
);
答案 1 :(得分:3)
clean函数使用htmlspecialchars
从字符串中清除html字符。但如果$data
是一个数组,它会调用自己来清理所有键和值。这就是为什么clean是递归的。
这种方法的优点是清洁函数可以透明地用于字符串和数组。
答案 2 :(得分:0)
它被称为recursion。
在您的示例中,$ _GET和$ _POST数组可能包含的元素也是可以包含数组的数组(ad infinitum)。所以你不知道要清理多少个子阵列。
要解决此问题,函数clean
的编写方式是在清理当前数组时它发生“子数组”时调用自身。它就像一个仅用于嵌套数据结构的循环。