gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:37:39 25 4
gpt4 key购买 nike

我最近将 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 变量的引用。

关于php - 升级到 5.6.x 后如何修复 php 中的引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com