note 40172 added to function.array-push

From: Date: Tue, 24 Feb 2004 07:48:22 +0000
Subject: note 40172 added to function.array-push
Groups: php.notes 
Request: Send a blank email to php-notes+get-65630@lists.php.net to get a copy of this message
The problem with array_push is that it is pass by value. If you are dealing with objects whose inner state may change at any time, you need a push and pop who return the actual objects, rather than copies of them. After some difficulty and board assistance, I have these methods. I've tested them, and they seem to work fine. function push(&$array, &$object){ $array[] =& $object; } function & pop(&$array){ return array_pop($array); } [Test Code] class TestObject{ var $value = 0; function getValue(){ return $this->value; } function setValue($mixed){ $this->value = $mixed; } } $myarr = array(); $tmp =& new TestObject(); $tmp2 =& new TestObject(); $tmp->setValue(2); $tmp2->setValue(3); function push(&$array, &$object){ $array[] =& $object; } function & pop(&$array){ return array_pop($array); } push($myarr, $tmp); push($myarr, $tmp2); $tmp->setValue(4); $tmp2->setValue(6); $val = pop($myarr); print "popped value: ".$val->getValue()."<br />"; print "values in internal array: <br />"; foreach ($myarr as $key=>$value){ print "key: $key, object: $value, value: "; print $value->getValue()."<br />"; } [/TestCode] ---- Manual Page -- http://www.php.net/manual/en/function.array-push.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40172 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40172&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40172&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65630) next »