user2209644
user2209644

Reputation: 711

Passing objects to functions in php

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'.

Upvotes: 3

Views: 77

Answers (2)

Asaph
Asaph

Reputation: 162771

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;
      }
}

Upvotes: 1

Evert
Evert

Reputation: 99505

To do what you want, you need to clone your object. If it feels wrong it's probably because what you're trying to do is not really correct.

I could propose a better solution, but I need to know what you're actually doing with these values.

Upvotes: 0

Related Questions