Jump to content

Create an object in a loop?


christo16

Recommended Posts

I realize this may be a better post for the oop forum but I figured there is more visibility here. I have a class that outputs an .ics (iCal file) and I want to create multiple .ics files in the same page.  I've setup a loop to create a new instance of the class but it creates one and then doesn't output anymore.  I figure because its trying to instantiate the object with the same variable.  Whats the best way to setup the loop so that I am creating new object on each loop?

Thank you!

Link to comment
https://forums.phpfreaks.com/topic/107104-create-an-object-in-a-loop/
Share on other sites

Some php code may help, but do you use a certain pattern. I think a factory pattern is quite usable in your case:

class icalGenerator{
  public function __construct(){}

  public function createIcal(){
    $ical = new iCal();
    $ical->doSomething();
    return $ical;
  }
}

class ical{
  public function __construct(){}
  public function __toString(){}
  public function doSomething(){}
}

You can use the classes in a loop:

$result = array( 12, 14, 19, 40, 89 ); //A list of event ids, for example.
$generator = new icalGenerator();

if( $result ){
  foreach( $result as $event ){
    $ical = $generator->createIcal( $event );
    echo $ical;
  }
}else
  throw new Exception( 'No events to display!' );

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.