我正在编写一个类来清理通过 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 ) {
关于PHP 传递数组作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27298298/