Avoid Recreation of object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Avoid Recreation of object

Post by anjanesh »

Code1 : This code displays details related to each element in the array $lines

Code: Select all

while (list($k,$v)=each($lines))
 {
 	$gb = new Class1($v);
 	// display $gb contents
 }
Code2 : This code displays details related to only the first in the array $lines

Code: Select all

$gb = new Class1();
while (list($k,$v)=each($lines))
 {
 	$gb->set($v);
 	// display $gb contents
 }
I was hoping Code2 will be faster because the object is created once while in Code 1 its recreated.

This how my contructor is :

Code: Select all

function Class1($Id=-1)
 {
 	if ($Id!=-1)
 	 $this->set($Id);
 }
function set($Id)
 {
 	$this->var1 = $Id;
 	$this->func();
 }
The output is a table where each row has some info related to $v.
Code1 works ok but Code2 displays the first row ok and the rest of the rows having row1's value.
Anyone know how this works ?
Using PHP 4 not PHP 5.

Thanks
Post Reply