user2209644 user2209644 - 4 days ago 5
PHP Question

Passing objects to functions in php

A php noob needs desperate help.

I have a static function in an object that does some stuff and returns an object like so:

$objectA = ObjectA::getItem();


Then i have a function that makes other types of objects and returns an array of them, part of these types of objects require the $objectA, so it gets passed in like so:

$arrayOfObjectB = ObjectB::getStuff($objectA);


When constructing the $arrayOfObjectB i change a part of $objectA which will be a part of $objectB
Something like this:

public static function getStuff($objectA)
{
$arrayOfObjectB = array();
foreach(...loops through some stuff)
{

$objectA->setSomething($variableChangedDuringLoop);
$objectB = new ObjectB($objectA);
$arrayOfObjectB[] = $objectB;
}
}


what happens is that all of the $objectA->something in $arrayOfObjectB will have set to the same thing as the last item in the loop, what i would like to happen is for the $something to hold separate values set during the loop.

I could clone the objects each time during the loop and then set them, that would work.
But this approach seems 'wrong'.

English is not my first language, so explaining this is kinda hard, kudos to those that were able to read this far.
Thanks.

Answer

When you pass a reference to $objectA to a function or a constructor, no copies of the object are made. If you make modifications to $objectA, you're affecting the same instance of the object as existed outside the the function (or constructor). If you want independent instances, you'll need to make a copy of the object. Something like this:

public static function getStuff($objectA)
{
    $arrayOfObjectB = array();
    foreach(...loops through some stuff)
      {
           // make a copy of $objectA
           $objectAClone = new ObjectA();
           $objectAClone->setX($objectA->getX());
           $objectAClone->setY($objectA->getY());
           ...
           $objectAClone->setSomething($variableChangedDuringLoop);
           $objectB = new ObjectB($objectAClone);
           $arrayOfObjectB[] = $objectB;
      }
}
Comments