我正在编写一个类来清理通过ajax调用传递给PHP的字符串,当我将字符串传递给此类时,它可以正常工作,但将数组作为引用传递,将无法工作。
class Sanitize {
public static function clean (&$str) {
self::start($str);
}
public static function cleanArray (&$array) {
if (self::arrayCheck($array)) {
foreach ($array as $key => $value) {
if (self::arrayCheck($value)) {
self::cleanArray($value);
} else {
self::clean($value);
}
}
} else {
throw new Exception ('An array was not provided. Please try using clean() instead of cleanArray()');
}
}
private static function start (&$str) {
$str .= '_cleaned';
}
private static function arrayCheck ($array) {
return (is_array($array) && !empty($array));
}
}
测试代码:
$array = array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four'
);
echo print_r($array, true) . PHP_EOL;
Sanitize::cleanArray($array);
echo print_r($array, true) . PHP_EOL;
输出:
Array
(
[one] => one
[two] => two
[three] => three
[four] => four
)
Array
(
[one] => one
[two] => two
[three] => three
[four] => four
)
是否有我缺少的东西,还是无法在PHP中嵌套引用传递?
您会在foreach中丢失参考。将其更改为此,它将起作用:
foreach( $array as $key => &$value ) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句