将属性插入对象

时间:2015-10-29 07:41:18

标签: php

我需要什么

我想在对象中添加一个新属性。

var_dump给出以下结果

 array (size=1)
0 => 
object(Item)[430]
  protected '_node' => null
  protected '_id' => 
    array (size=1)
      'ItemId' => string '4596' (length=4)
  protected '_data' => 
    array (size=8)
      'ItemId' => string '4596' (length=4)
      'Id' => string '1055' (length=4)
      'employee' => string '40' (length=2)
      'project' => string '73' (length=2)
      'activity' => string '473' (length=3)
      'date' => string '2015-09-28' (length=10)
      'duration' => string '28800' (length=5)
      'comment' => null
  protected '_values' => 
    .
    .
    .

我想在对象中添加另一个属性customer,以便对象看起来像这样

 array (size=1)
0 => 
object(Item)[430]
  protected '_node' => null
  protected '_id' => 
    array (size=1)
      'ItemId' => string '4596' (length=4)
  protected '_data' => 
    array (size=8)
      'ItemId' => string '4596' (length=4)
      'Id' => string '1055' (length=4)
      'employee' => string '40' (length=2)
      'project' => string '73' (length=2)
      'activity' => string '473' (length=3)
      'date' => string '2015-09-28' (length=10)
      'duration' => string '28800' (length=5)
      'comment' => null
      'customer' => string '20' (length=2)
  protected '_values' => 
    .
    .
    .

我该怎么做?

修改

print_r()返回

  Array
    (
   [0] => Item Object
      (
        [_node:protected] => 
        [_id:protected] => Array
            (
                [ItemId] => 4596
            )

        [_data:protected] => Array
            (
                [ItemId] => 4596
                [Id] => 1055
                [employee] => 40
                [project] => 73
                [activity] => 473
                [date] => 2015-09-28
                [duration] => 28800
                [comment] => 
            )

        [_values:protected] => Array

1 个答案:

答案 0 :(得分:0)

正如我所看到的,customer不是属性,而是$_data属性中哈希的关键。那么

$object->_data['customer'] = '20';

由于$_data属性为protected,您必须在类或派生词中执行此操作。