note 40172 deleted from function.array-push by peehaa
| From: | peehaa@php.net | Date: | Tue, 21 Mar 2017 08:38:43 +0000 |
| Subject: | note 40172 deleted from function.array-push by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208920@lists.php.net to get a copy of this message | ||
Note Submitter: aron
----
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]
?>