在使用PHP数组存储对象 [英] Storing objects in an array with php

查看:151
本文介绍了在使用PHP数组存储对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库的内容 - > ID和内容 - 拉行的功能>类型是他们用来动态调用在amethod方法已经载入的模型来获取和格式化对象的详细信息。一旦返回的对象被添加到阵列。一切都很好,只是当我来到使用数组虽然它有它的项目的正确数目,它们都含有同一个对象,虽然我知道他们将返回不同的。林在这一个完全丧失,任何帮助/想法对子级是伟大的!

在code是如下:

 的foreach($查询 - >的结果()为$内容)
{
    $项目= $这个 - > {'mod_'$内容 - 方式>类型} - >获得($内容 - > ID);
    的print_r($项目);
    $项目[] = $项目;
}
的print_r($项目);

而print_r的语句产生这样的:

  stdClass的对象

    [ID] =>三十
    [类型] = GT;页
)stdClass的对象

    [ID] => 29
    [类型] = GT;页
)排列

    [0] => stdClass的对象
        (
            [ID] => 29
            [类型] = GT;页
        )    [1] => stdClass的对象
        (
           [ID] => 29
           [类型] = GT;页
        ))


解决方案

我猜想,问题是,你从参考的得到相同的对象每次的 获得函数,然后通过引用的补充它的的数组,导致阵列中的所有项目时,该项目在 GET <被修改被修改/ code>功能。如果是这样的话,下面的应该工作:

 的foreach($查询 - &GT;的结果()为$内容)
{
    $项目= $这个 - &GT; {'mod_'$内容 - 方式&gt;类型} - &GT;获得($内容 - &GT; ID);
    的print_r($项目);
    $项目[] = $克隆项目;
}
的print_r($项目);

I have a function that pulls rows from a database, the content->id and content->type are them used to dynamically call amethod in an already loaded model to get and format the objects details. Once the object is returned it is added to array. All is well except that when i come to use the array although it has the correct number of items in it, they all contain the same object even though i know that they are returned different. Im at a complete loss with this one, any help/ideas whould be great!

The code is below:

foreach($query->result() as $content)
{
    $item = $this->{'mod_'.$content->type}->get($content->id);
    print_r($item);
    $items[] = $item;
}
print_r($items);

And the print_r statements produce this:

stdClass Object
(
    [id] => 30
    [type] => page
)

stdClass Object
(
    [id] => 29
    [type] => page
)

Array
(
    [0] => stdClass Object
        (
            [id] => 29
            [type] => page
        )

    [1] => stdClass Object
        (
           [id] => 29
           [type] => page
        )

)

解决方案

I would guess that the problem is that you get to the same object every time by reference from the get function and then add it by reference to the array, resulting in all items in the array being modified when the item gets modified in the get function. If that is the case, the following should work:

foreach($query->result() as $content)
{
    $item = $this->{'mod_'.$content->type}->get($content->id);
    print_r($item);
    $items[] = clone $item;
}
print_r($items);

这篇关于在使用PHP数组存储对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆