簡體   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