更新指定数组中的对象还会更新包含相同ID对象的数组

时间:2015-02-06 21:22:56

标签: php arrays

如果标题令人困惑或措辞不好,我很抱歉,我对编程术语相对较新,无法想到更好的描述。

这是脚本的基本结构,删除了无关的函数/变量:

class User {

    public $username;
    public $binders;

    function __construct($username, $binders) {
        $this->username = $username;
        $this->binders = $binders;
    }
}

变量$bindersBinder个对象的数组:

class Binder {

    public $name;
    public $contents;

    function __construct($name, $contents = array()) {
        $this->name = $name;
        $this->contents = $contents;
    }
}

变量$contentsCard个对象的数组:

class Card {

    public $id;
    public $quantity;

    function __construct($id, $quantity = 0) {
        $this->id = $id;
        $this->quantity = $quantity;
    }

}

所以一个简单的结构可能是:

$users = array(
    'TestName' => new User('TestName', array(
        'BinderName1' => new Binder('BinderName1', array(
            'CardID_1' => new Card('1', '20'),
            'CardID_3' => new Card('3', '10'),
        ),
        'BinderName2' => new Binder('BinderName2', array(
            'CardID_1' => new Card('1', '7')
        )
    )
);

我目前正在尝试使用以下代码更新活页夹idBinderName1为1的卡片数量:

$users['TestName']->binders['BinderName1']->contents['CardID_1']->quantity = 5;

但是,当我在应用更改后使用print_r($users)时,响应会显示BinderName1BinderName2中的CardID_1更新数量。我是否错误地应用了更改?

编辑:似乎只有在我创建对象的克隆时才会出现这种情况,例如:

$card = $users['TestName']->binders['BinderName1']->contents['CardID_1'];
$cloneCard = clone $card;
array_push($users['TestName']->binders['BinderName1']->contents, $cloneCard);

0 个答案:

没有答案