0

I am trying to create multiple instances of an object as this was how the wrapper was designed to work. Now my problem is that I wanted to add a counter in the object declaration so that I will just have to loop through my data and create the necessary object for it and also loop it again for the wrapper to read them all.

Currently, I have this:

if(sizeof($product_name) > 0){
                for($counter=0;$counter<sizeof($product_name);$counter++){
                    $lineitem.$counter = new LineItem($this->_xi);
                    $lineitem.$counter->setAccountCode('200')
                        ->setQuantity($product_qty[$counter])
                        ->setDescription($product_name[$counter])
                        ->setUnitAmount($product_price[$counter]);
                    print_r($lineitem.$counter);
                }
            }

print_r($lineitem0);

My print_r returns nothing for both inside and outside the loop.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
hungrykoala
  • 1,083
  • 1
  • 13
  • 28

1 Answers1

1

Your problem is not really about OOP, but more about php. You want to create dynamic variable name to store all the instances of your class you are creating, you should do:

if(sizeof($product_name) > 0){
  for($counter=0;$counter<sizeof($product_name);$counter++){
      ${"$lineitem$counter"} = new LineItem($this->_xi);
      ${"$lineitem$counter"}->setAccountCode('200')
        ->setQuantity($product_qty[$counter])
        ->setDescription($product_name[$counter])
        ->setUnitAmount($product_price[$counter]);
                print_r(${"$lineitem$counter"});
  }
}

print_r(${"$lineitem" . 0});

Have a look at this question: Dynamic variable names in PHP

Community
  • 1
  • 1
olibiaz
  • 2,551
  • 4
  • 29
  • 31