Array of objects

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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!

Re: Array of objects

Marko wrote:
Quoted text here. Click to load it

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

$bar->title = "bar" ;
$bar->index = $i;


Re: Array of objects

Quoted text here. Click to load it

You're right! I changed it and everything is working properly. Thanks!

Re: Array of objects

On Thu, 05 May 2005 14:21:24 +0200, Marko wrote:

Quoted text here. Click to load it

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:

    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

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.

Site Timeline