2

Since I started to write more code in OOP I always run into a in my point of view "code styling" problem. I want to add some additional data to an existing object. When I used arrays this was easily possible with foreach because every array item got its own key. Now with objects I didn't found a way how I can access each item with an key.

$data_items = $this->model->get_function();
$data_items = (array) $data_items;
foreach ($data_items as $key => $row)
{
      $data_items[$key]['additional_data'] = 'additional_data';                      
}
$data_items = (object) $data_items;

I think my code is only a work around. Can please somebody tell me if I can get rid off the code line "$data_items = (array) $data_items;" and "$data_items = (object) $data_items;".

Thanks to everybody who replied to my question!

Until now I didn't realized that it is so easy what I tried to achieve:

foreach ($data_items as $row)
{
    $row->additional_data = 'additional_data';
}
4

4 回答 4

2

从数据处理的角度来看,对象和数组看起来几乎相同。您可以简单地添加另一个对象属性并将数据保存到其中,而无需声明所述属性(在我看来,这是一个缺点,但在您的情况下 - 一个优势)。

大批:

$arr = array();
$arr['additional_data'] = 'foo';

目的:

$obj = new stdClass;
$obj->additional_data = 'bar';

Foreach 将像处理数组键一样处理对象属性。并且不需要隐式转换。

这是无演员阵容:

$data_items = $this->model->get_function();
foreach ($resource_contacts as $key => $row)
{
      // Note, $data_items->{$key} must be an object, or this will crash.
      // You can check if it is with is_object() and react accordingly
      $data_items->{$key}->additional_data = 'additional_data';                      
}
于 2013-07-09T13:51:23.213 回答
2

如果对象实现了Traversable接口 ( ArrayAccess, Iterable),如stdClass,您可以轻松地foreach创建实例:

$foo = new stdClass;
$foo->bar = 'foobar';
foreach($foo as $property => $value)
{
    echo '$foo->'.$property.' === '.$value;
    echo $foo->{$property} = 'reassign';
}

如果不实现这些接口,您仍然可以迭代任何对象,但是:只有公共属性是可见的。
为了解决这个问题,我倾向于将我的所有属性声明为受保护,并让我的所有数据对象都从实现Iterator接口的抽象模型继承,因此我不必担心。

于 2013-07-09T13:53:11.017 回答
0

你应该能够做这样的事情:

$data_items = $this->model->get_function();
foreach ($resource_contacts as $key => $row)
{
      $data_items->$key->additional_data = 'additional_data';                      
}
于 2013-07-09T13:55:25.637 回答
0

使用引用能够在foreach循环内修改您的对象,如果这是您想要实现的目标:

foreach($objectList as &$obj){
    $obj->newProperty = 'whatever';
}
于 2013-07-09T13:58:50.307 回答