Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects to functions in php

Tags:

oop

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

like image 531
user2209644 Avatar asked Apr 14 '26 07:04

user2209644


1 Answers

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;
      }
}
like image 100
Asaph Avatar answered Apr 16 '26 19:04

Asaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!