NYCPHP Meetup

NYPHP.org

[nycphp-talk] array of object being passed by reference problem

Jeff Barrett jeffb at uniquephoto.com
Fri Dec 5 10:36:21 EST 2003


I have the following test script:

<?php

class testObj{

	var $junk;
	var $objs;

	function testObj()
	{
	}

	function populate()
	{
		for( $i = 0; $i < 5; $i++ )
		{
			$o = &new testObj();
			$o->setVar($i);
			$this->objs[] = $o;
		}
	}

	function setVar( $id )
	{
		$this->junk = $id;
		print "set ".$this->junk."<br>";
	}

	function getObjs()
	{
		return $this->objs;
	}

	function printall()
	{
		foreach($this->objs as $pos => $o )
		{
			print "print ".$o->junk."<br>";
		}
	}
}

$obj = new testObj();

$obj->populate();

$objs = &$obj->getObjs();

print "<br>";

foreach($objs as $pos => $o )
{
	print $o->junk."<br>";
}

foreach( $objs as $pos => $o )
{
	$o->setVar("aa".$pos);
	print "<br>";
}

foreach( $objs as $pos => $o )
{
	print $o->junk."<br>";
}

$obj->printall();

?>

Which is putting out the following to the screen:

set 0
set 1
set 2
set 3
set 4

0
1
2
3
4
set aa0

set aa1

set aa2

set aa3

set aa4

0
1
2
3
4
print 0
print 1
print 2
print 3
print 4

The problem, after the set aa0...aa4 lines I should not be seeing 0...4 and
print 0...print 1. I should be seeing aa0...aa4 and print aa0...print aa4.
The problem seems to lie in how I am passing the array of objects to the
calling program and then having those changes be a part of the object, seems
like I am just changing a copy of the object since the changes are not
sticking. Any help with this would be greatly appreciated.

Thanks,

Jeff Barrett
Email: jeffb at uniquephoto.com
IM:    jeffreyabarrett
Phone: 973-377-5555 ext 205





More information about the talk mailing list