PHP在递归函数中按引用传递不起作用 [英] PHP pass by reference in recursive function not working

查看:55
本文介绍了PHP在递归函数中按引用传递不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数用于在深度嵌套的对象/数组组合中添加或删除斜杠.数组的第一个级别"总是一个对象,但它的一些属性可能是数组或对象.

I have two functions that I'm using to add or remove slashes from a deeply nested object/array combo. The first "level" of the array is always an object, but some of its properties may be arrays or objects.

这是我的两个功能:

function objSlash( &$obj, $add=true )
{
    foreach ( $obj as $key=>$field )
    {
        if ( is_object( $field ) )
            objSlash( $field, $add );
        else if ( is_array( $field ) )
            arrSlash( $field, $add );
        else if ( $add )
            $obj->$key = addslashes( $field );
        else
            $obj->$key = stripslashes( $field );
    }

    return;
}

function arrSlash( &$arr, $add=true )
{
    foreach ( $arr as $key=>$field )
    {
        if ( is_object( $field ) )
            objSlash( $field, $add );
        else if ( is_array( $field ) )
            arrSlash( $field, $add );
        else if ( $add )
            $arr[$key] = addslashes( $field );
        else
            $arr[$key] = stripslashes( $field );
    }

    return;
}

被这样称呼:

objSlash( $obj, false );

但是,该函数不会从嵌套数组中去除斜线.传入函数的对象是这样的:

However, the function does not strip the slashes from the nested array. The object passed into the function is like this:

stdClass Object
(
    [id] => 3
    [lines] => Array
        (
            [0] => Array
                (
                    [character] => Name
                    [dialogue] => Something including \"quotes\"
                )
        )
)

我做错了什么?沿线的某个地方缺少参考...

What have I done wrong? Somewhere along the line a reference is going missing...

推荐答案

foreach 使用数组/对象的副本而不是数组/对象本身:

foreach uses a copy of the array/object and not the array/object itself:

注意:除非数组被引用, foreach 对指定数组的副本而不是数组本身进行操作.foreach 对数组指针有一些副作用.不要在 foreach 期间或之后依赖数组指针而不重置它.

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

所以使用参考:

foreach ($arr as $key => &$field) {
    // …
}

或者像 Kuroki Kaze 建议的那样使用数组元素/对象属性本身,使用 $arr[$key] 而不是它的复制值 $field.

Or use the array element/object property itself like Kuroki Kaze suggested by using $arr[$key] instead of its copied value $field.

这篇关于PHP在递归函数中按引用传递不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆