Assigning object property inside a foreach loop; data does not persist outside foreach loop. Why not? INT and STRING assignment does work

StackOverflow https://stackoverflow.com/questions/14224411

  •  14-01-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

On top, outside for loop add:

$filler = array();

Inside for loop add this:

$filler[] = $data[$i]->data->proj_hours;

Then try to dump data afterwards.

print_r($filler);

Hope that will bring you some results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top