note 27788 deleted from function.array-walk by aidan
| From: | aidan@php.net | Date: | Sun, 11 Jul 2004 02:09:40 +0000 |
| Subject: | note 27788 deleted from function.array-walk by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-73035@lists.php.net to get a copy of this message | ||
Note Submitter: RNova@no-spam-pleasegmx.net
----
CALLING BACK A FUNCTION OF AN OBJECT:
Pass an array as the second parameter to array_walk.
Don't put a copy of the object into the first array value, but a _reference_ to it!
Otherwise
(a) if your callback function has side effects on the object (i.e. changes object data other
than the elememts of the array you are walking), the side effects will apply to the copy of your
object and will _not_ affect your object, and
(b) you waste time and memory by unneccessarily creating the copy.
The following example shows naive use (as I did the first time) and correct use:
class Wallet {
var $coins;
var $total;
function Wallet($coins) {
$this->coins = $coins;
$this->calculateTotal_naive();
}
function calculateTotal_naive() {
array_walk( $this->coins, array( $this,'addCoin') );
}
function calculateTotal_correct() {
$a = array();
$a[0] =& $this;
$a[1] = 'addCoin';
array_walk( $this->coins, $a );
}
function addCoin( &$item, $key ) {
$this->total += $item;
}
}
$wallet =& new Wallet( array( 1, 2, 2, 5 ) );
echo $wallet->total."<HR>\n";
$wallet->calculateTotal_correct();
echo $wallet->total;