繁体   English   中英

如何在升级到5.6.x后修复php中的引用传递

[英]How to fix pass by reference in php after upgrading to 5.6.x

我最近将fom php 5.2升级到5.6,还有一些我无法解决的代码:

//Finds users with the same ip- or email-address
function find_related_users($user_id) {
    global $pdo;

    //print_R($pdo);

    //Let SQL do the magic!
    $sth = $pdo->prepare('CALL find_related_users(?)');
    $sth->execute(array($user_id));
    //print_R($sth);
    //Contains references to all users by id, to check if a user has already been processed
    $users_by_id = array(); 

    //Contains arrays of references to users by depth
    $users_by_depth = array();

    while ($row = $sth->fetchObject()) {
        //Create array for current depth, if not present
        if (!isset($users_by_depth[$row->depth])) 
            $users_by_depth[$row->depth] = array();

        //If the user is new
        if (!isset($users_by_id[$row->id])) {
            //Create user array
            $user = array(
                'id' => $row->id,
                'name' => $row->name,
                'email' => $row->email,
                'depth' => $row->depth,
                'adverts' => array()
            );

            //Add all users to depth array
            @array_push($users_by_depth[$row->depth], &$user);

            //Add references to all users to id array (necessary to check if the id has already been processed)
            $users_by_id[$row->id] = &$user;
        }
        //If user already exists
        else 
            $user = &$users_by_id[$row->id];

        //Add advert to user
        if ($row->advert_id != null)
            array_push($user['adverts'], array(
                'id' => $row->advert_id,
                'title' => $row->advert_title,
                'msgs' => $row->msgs,
                'url' => $row->url
            ));
        #print_r($user);
        //Unset $user variable !!! 
        //If this is missing, all references in the array point to the same user
        unset($user);
    }

    //Return users, grouped by depth
    return $users_by_depth;
}

如果我只是在美元符号之前删除&符号,则该函数将停止按预期工作。 从stackoverflow上的其他问题我发现这是一个引用调用,并将为新的PHP版本制动。 但是我找不到解决方案了。

感谢您提供有关如何更新php 5.6.x此代码的任何帮助

您的代码可能永远不会像您认为的那样工作,因为您正在抑制array_push()调用上的错误。 请注意,只有array_push()的第一个参数通过引用传递,其他值总是按值传递。

你应该删除错误抑制器@ (永远不要在你自己的代码中使用它),在这种情况下你也可以这样做:

$users_by_depth[$row->depth][] = &$user;
                            ^^ add an element just like `array_push`

现在, $users_by_depth新值将包含对$user变量的引用。

暂无
暂无

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

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