douchan4674 2013-01-08 21:34
浏览 30
已采纳

在foreach循环中分配对象属性; 数据不会在foreach循环之外持续存在。 为什么不? INT和STRING分配确实有效

Been knocking my head off the desk on this one all day.

    // Iterate over project array to populate release data
    for ($i = 0; $i < count($data); $i++) {
        $data[$i]->setProjectReleaseSchedule( $proj_scheds[$i] );

            //Get each projects Est and Act hours
            $options = new stdClass;
            $options->default       = true;
            $options->project_id    = $data[$i]->getProjectId();
            $options->department_id = $person_dm->getPersonDepartmentId();

            //works; AKA: property get assigned an int thatr incriments evern loop
            //$data[$i]->data->proj_hours = $this->counter++;

            //$weekly_report_dm->getProjectHours returns an object w/ populated properties
            $data[$i]->data->proj_hours = $weekly_report_dm->getProjectHours($options);

            //As a test, this dumps what is expected...
            echo'<pre>';
            print_r( $data[$i]->data->proj_hours );
            echo'</pre>';

    }


echo'<pre>';
//After the loop completes and I try to dump the data the property $data->data->proj_hours is assigned an object..
//but the object properties are all null :(.
print_r( $data );
echo'</pre>';
exit;

So as you can see Im looping over an array of objects; for each object I got another method for data, it returns with expected data. The "print_r( $data[$i]->data->proj_hours );". However, once the loop finishes and I try to dump the data the object is assigned to the parent, but the properties of said object are null/blank.

So the question: Why can I assign INTs, STRINGS, etc to an objects property and they persist outside the foreach loop. But an objects properties when assigned to a parent object inside a foreach loop, the values do not persist?

  • 写回答

2条回答 默认 最新

  • donglan8256 2013-01-09 08:46
    关注

    It seems that weekly_report_dm->getProjectHours($options) returns reference to same private (?) property , which changes each call. You can try to clone the result with clone :

    $data[$i]->data->proj_hours = clone $weekly_report_dm->getProjectHours($options);
    

    Changing getProjectHours to not return reference would be the right solution

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100