By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,729 Members | 1,433 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,729 IT Pros & Developers. It's quick & easy.

Array of objects

P: n/a
Hi! I'm a C++ programer that just recently started writing some scripts in
php. I don't understand why the following code doesn't word:

for($i = 0; $i < 10; $i++)
{
$bar.$title = "Bar";
$bar.$index = $i;

$bars[] = $bar;
}

foreach($bars as $bar)
echo($bar.$title . $bar.$index . "<br>");

It prints Bar9 ten times. Why? How to get it to work properly?

Using php version 4.3.9. Thanks!
Jul 17 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
MRB
Marko wrote:
Hi! I'm a C++ programer that just recently started writing some scripts in
php. I don't understand why the following code doesn't word:

for($i = 0; $i < 10; $i++)
{
$bar.$title = "Bar";
$bar.$index = $i;

$bars[] = $bar;
}

foreach($bars as $bar)
echo($bar.$title . $bar.$index . "<br>");

It prints Bar9 ten times. Why? How to get it to work properly?

Using php version 4.3.9. Thanks!

You're using the wrong syntax, use the following to access objects members:

$bar->title = "bar" ;
$bar->index = $i;
Cheers
Jul 17 '05 #2

P: n/a
> You're using the wrong syntax

You're right! I changed it and everything is working properly. Thanks!
Jul 17 '05 #3

P: n/a
On Thu, 05 May 2005 14:21:24 +0200, Marko wrote:
foreach($bars as $bar)
echo($bar.$title . $bar.$index . "<br>");

It prints Bar9 ten times. Why? How to get it to work properly?

Using php version 4.3.9. Thanks!


The "." is string concatenation, not member reference. That would be "->".
Also, you are assigning to the same variable bar. Your code will not work
because objects are references and you are always trying to use the same
object. That will set the whole array to the same value. You would
probably want something like this:

#!/usr/local/bin/php
<?php
class cls {
public $title = "";
public $index = "";
}
for ($i = 0;$i<10;$i++) {
$bar = new cls();
$bar->title = "Bar";
$bar->index = $i;
$bars[] = $bar;
}
foreach($bars as $bar) echo ($bar->title.$bar->index."\n");
?>

If I understood you correctly, this is what you want:
$ ./ttt.php
Bar0
Bar1
Bar2
Bar3
Bar4
Bar5
Bar6
Bar7
Bar8
Bar9

Unfortunately, I am no longer using PHP4 and I don't have it on the system.

--
Egoist: A person of low taste, more interested in themselves than in me.

Jul 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.