note 11676 modified in Classes and Objects by jmcastagnetto

From: Date: Thu, 01 Mar 2001 23:31:29 +0000
Subject: note 11676 modified in Classes and Objects by jmcastagnetto
Groups: php.notes 
Request: Send a blank email to php-notes+get-11757@lists.php.net to get a copy of this message
[Editor's note: It is understandable that your original loop will not work, you are getting a *copy* of the object, not the original object itself. A loop such: for ($i=0; $i<count($header); $i++) $header[$i]->set_i('new string'); will access the object directly, instead of the copy you get w/ foreach.] Array of Objects First here is a simple class: class text { var $i; function text($i = 'default') { $this->i = $i; } function set_i( $i ) { $this->i = $i; } } Now create objects and put them in an array $header[] = new text('foo'); $header[] = new text('bar'); The following will NOT work: foreach($header as $i): $i->set_i('new string'); endforeach; You must do the following instead: $j = 0; foreach($header as $i): $k = &$header[$j++]; $k->set_i('new string'); endforeach; It's quirky. Does anyone know of a better way to do this? http://www.php.net/manual/classes-and-objects.php

« previous php.notes (#11757) next »