note 40172 modified in function.array-push by vrana

From: Date: Tue, 17 Aug 2004 14:48:12 +0000
Subject: note 40172 modified in function.array-push by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80054@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. <?php 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); 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] ?> --was-- 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] http://php.net/manual/en/function.array-push.php

« previous php.notes (#80054) next »