简体   繁体   English

PHP传递数组作为参考

[英]PHP Passing array as reference

I am writing a class to sanitize strings passed to PHP through an ajax call, when I pass a string into this class it works fine but passing the array as a reference and it won't work. 我正在编写一个类来清理通过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));
    }
}

Test Code: 测试代码:

$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;

Output: 输出:

Array
(
    [one] => one
    [two] => two
    [three] => three
    [four] => four
)

Array
(
    [one] => one
    [two] => two
    [three] => three
    [four] => four
)

Is there something I am missing, or is it not possible to nest reference passes in PHP? 是否有我遗漏的东西,或者是否无法在PHP中嵌套引用传递?

Your code does not modify the $array , it modifies $value . 您的代码不会修改$array ,它会修改$value

There're couple of ways to get around that, one is foreach ($array as &$value) , the other is modify $array[$key] inside the loop. 有几种方法可以解决这个问题,一种是foreach ($array as &$value) ,另一种是在循环内修改$array[$key]

You lose the reference inside the foreach. 你失去了foreach内部的引用。 Change it to this and it'll work: 将其更改为此并且它将起作用:

foreach( $array as $key => &$value ) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM