Page 1 of 1

array_push - pass by reference: does it exist?

Posted: Mon Feb 23, 2004 1:01 am
by angrytuna
Hello the forum,
It was fairly horrific figuring out why this was malfunctioning, but I finally understood that the array_push function is pass by value, not by reference. The problem lies in that I am trying to store objects in the array I am pushing to, and subsequent changes to the objects are not reflected if the object is copied. The following code demonstrates:

Code: Select all

<?php
class TestObject{
	var $value = 0;
	function getValue(){
		return $this->value;
	}
	function setValue($mixed){
		$this->value = $mixed;
	}
}
$myarr = array();
$tmp = new TestObject();
$tmp->setValue(1);
array_push($myarr, $tmp);
$tmp->setValue(2);
$uncertain = array_pop($myarr);
print "value in internal array: ".$uncertain->getValue();
?>
Does anyone know if a pass-by-reference version of array_push exists? I am using version 4.3.3. I know this problem is supposed to be fixed in version 5, but that's unfortunately not an option just yet...

Any help is appreciated.

AT

Posted: Mon Feb 23, 2004 1:26 am
by markl999
If you're only pushing one value then it's usually better (and slightly faster) to use []. Eg

Code: Select all

<?php
class TestObject{
   var $value = 0;
   function getValue(){
      return $this->value;
   }
   function setValue($mixed){
      $this->value = $mixed;
   }
}
$myarr = array();
$tmp =& new TestObject();
$tmp->setValue(1);
//array_push($myarr, $tmp);
$myarr[] =& $tmp;
$tmp->setValue(2);
$uncertain = array_pop($myarr);
print "value in internal array: ".$uncertain->getValue();
?>

Posted: Mon Feb 23, 2004 2:35 am
by angrytuna
That's exactly what I was looking for, thank you. Do you by chance have links to where I could read more about that? The syntax was a bit confusing:

Code: Select all

<?php
$myarr[] =& $tmp;
?>
This means dereference and assign, yes? I need to know, because in my actual code I am pushing a large amount of objects onto an array.

Thanks for your help so far; I look forward to your response.

AT

[edited]
Ok, I found part of it:
http://www.php.net/manual/en/language.r ... .unset.php
How does that work in conjunction with the array brackets?

[edited again]
Never mind, I've got it now. That whole section was a very good read.

Thanks again!

AT