PHP变量不充当参考

时间:2018-07-10 23:17:08

标签: php reference

<?php
class User {
    public $id;
    public $counter;
    public $removed;
}
$dB = json_decode(file_get_contents('dataBase.json'), true);
$dataBase = &$dB['noob'];
$userInDB = null;
$user = array('id' => (int)$_GET['id'], 'counter' => (int)$_GET['counter'], 'removed' => (bool)$_GET['removed']);
foreach ($dataBase as $usr) {
    if ($usr['id'] == $user['id']) {
        $userInDB = &$usr;
        break;
    }
}
if ($userInDB) {
    $userInDB['counter'] = $userInDB['counter'] + $user['counter'];
    $userInDB['removed'] = $user['removed'];
    print_r($userInDB);
} else {
    $dataBase[] = $user;
    print_r($dataBase);
}
if(isset($_GET['id'])) { 
    $json = json_encode($user);
    $updateddB = json_encode($dB);
    file_put_contents('dataBase.json', $updateddB);
}
?>

除我尝试在数组中编辑值的部分外,所有内容均有效。 $ userInDB已更改,但是即使在我确定已引用的情况下,它在$ dB内引用的部分也未更改。有人请帮忙,我的头已经打结了。

1 个答案:

答案 0 :(得分:0)

您有以下循环:

foreach ($dataBase as $usr) {
    if ($usr['id'] == $user['id']) {
        $userInDB = &$usr;
        break;
    }
}

$userInDB是对$usr的引用,但是$usr只是由foreach循环创建的,并未引用它正在循环的原始数组。举例来说,您有一个非常简单的案例:

foreach ($foo as $var) {
    $var++;
}

这根本不影响$foo

您需要做的是直接引用$dataBase变量:

foreach ($dataBase as $key => $usr) {
    if ($usr['id'] == $user['id']) {
        $userInDB = &$dataBase[$key];
        break;
    }
}