[英]How to fix pass by reference in php after upgrading to 5.6.x
I recently upgraded fom php 5.2 to 5.6 and there is some code I could not fix yet: 我最近将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;
}
If I simply remove the ampersand before the dollar sign, the function stops to work as intended. 如果我只是在美元符号之前删除&符号,则该函数将停止按预期工作。 From other questions on stackoverflow I found that this is a call by reference and will brake for new php versions.
从stackoverflow上的其他问题我发现这是一个引用调用,并将为新的PHP版本制动。 However I could not find a solution yet.
但是我找不到解决方案了。
Thank you for any help on how to update this code for php 5.6.x 感谢您提供有关如何更新php 5.6.x此代码的任何帮助
Your code was probably never working as you thought it was as you are suppressing the errors on your array_push()
call. 您的代码可能永远不会像您认为的那样工作,因为您正在抑制
array_push()
调用上的错误。 Note that only the first parameter of array_push()
is passed by reference, the other values are always passed by value. 请注意,只有
array_push()
的第一个参数通过引用传递,其他值总是按值传递。
You should remove the error suppressor @
(never use that in your own code) and in this case you can also do: 你应该删除错误抑制器
@
(永远不要在你自己的代码中使用它),在这种情况下你也可以这样做:
$users_by_depth[$row->depth][] = &$user;
^^ add an element just like `array_push`
Now your new value in your $users_by_depth
will contain a reference to the $user
variable. 现在,
$users_by_depth
新值将包含对$user
变量的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.