Welcome to WebmasterWorld Guest from 54.166.114.43

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Looping through existing objects of a class

Using print()?

   
10:43 am on Mar 14, 2012 (gmt 0)

10+ Year Member



For practice, I'm trying to print all concert data and split them up depending on if they are an upcoming/future show or a past show. Here is an example:

$liveShow7 = new Concert("2013-07-23", "Rovaniemi", "Finland", "Grande", "The Howl, Sinfect");
$liveShow6 = new Concert("2010-03-31", "Oulu", "Finland", "Hevimesta", "Synesthesia");
$liveShow5 = new Concert("2009-12-03", "Raahe", "Finland", "Rytmikellari", "-");


If needed, I can post the full code, but at the moment everything works when I call the above in this manner:

<?php $liveShow2->show("past"); ?>
<?php $liveShow5->show("past"); ?>


The show() method is used to select the type of shows to display ("upcoming" | "past"), and works also.

Now, what I want to do, is to loop through all of those n+1 instances of $liveShow# (where # = number 1, 2, 3, ..., total amount). This is what I think should do it, but alas, doesn't:


for($j=1; $j>=$numberConcerts; $j++) {
print ${"liveShow".$j}->show("past"); // I also tried ${$liveShow.$j and ${$"liveShow".$j)
}


What I'm hoping for it to do is to generate these calls as PHP code and run them, if 0<$j<5:

$liveShow1->show("past");
$liveShow2->show("past");
$liveShow3->show("past");
$liveShow4->show("past");



But it seems like it ignores the method call, and displays nothing. Any tips? Thanks!
12:58 pm on Mar 14, 2012 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



Just out of curiosity, why aren't you storing these in an array of objects?

e.g.:


$shows = array();
$shows[] = new Concert("2013-07-23", "Rovaniemi", "Finland", "Grande", "The Howl, Sinfect");
$shows[] = new Concert("2010-03-31", "Oulu", "Finland", "Hevimesta", "Synesthesia");
$shows[] = new Concert("2009-12-03", "Raahe", "Finland", "Rytmikellari", "-");

foreach($shows as $show) {
$show->show("past");
}


IMO, there is never a good reason to use variable variables like this.
1:16 pm on Mar 14, 2012 (gmt 0)

10+ Year Member



Ah, that sounds like a good way to do it, thanks! The only reason I didn't is that I wasn't aware of how to do it :) Self-learning by search engines is sometimes quite frustrating...
 

Featured Threads

Hot Threads This Week

Hot Threads This Month