note 27788 added to function.array-walk
| From: | RNova at no-spam-pleasegmx dot net | Date: | Wed, 18 Dec 2002 18:34:09 +0000 |
| Subject: | note 27788 added to function.array-walk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-41076@lists.php.net to get a copy of this message | ||
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;
--
http://www.php.net/manual/en/function.array-walk.php
http://master.php.net/manage/user-notes.php?action=edit+27788
http://master.php.net/manage/user-notes.php?action=delete+27788
http://master.php.net/manage/user-notes.php?action=reject+27788