如何在PHP中连接一个对象声明的计数器


how to concat a counter for an object declaration in PHP

我试图创建一个对象的多个实例,因为这是包装器的设计工作方式。现在我的问题是,我想在对象声明中添加一个计数器,这样我就只需要循环我的数据,并为它创建必要的对象,并再次循环它,以便包装器读取它们。

目前,我有这个:

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在循环内和循环外都不返回任何值

你的问题不是OOP,而是php。如果您想创建动态变量名来存储您正在创建的类的所有实例,您应该这样做:

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});
PHP中的动态变量名