array_push - pass by reference: does it exist?

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
angrytuna
Forum Newbie
Posts: 12
Joined: Mon Feb 23, 2004 1:01 am

array_push - pass by reference: does it exist?

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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();
?>
User avatar
angrytuna
Forum Newbie
Posts: 12
Joined: Mon Feb 23, 2004 1:01 am

Post 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
Post Reply