Page 1 of 1
reference problem
Posted: Wed Nov 03, 2004 6:32 pm
by mudkicker
Code: Select all
<?php
class BlockRenderer {
var $blocks = array();
function addBlock(& $block) {
$this->blocks[] = & $block;
}
function render() {
foreach ( $this->blocks as $key => $block ) {
// foreach (in PHP4) makes copies not references to variables,
// hence the $key is used, not the $block
$this->blocks[$key]->draw();
}
}
}
?>
This example is confused my mind and taken from phppatterns.com as I was reading some articles about design patterns.
Now, why did the auther use a
& (reference) by addBlock function?
Why is this useful? Is it necessary? Can someone explain me this?
(please don't give me the link of references in php manual..)
Posted: Wed Nov 03, 2004 6:39 pm
by timvw
well, it"s all about performance...
if the object would be copied, it would consume more memory, and take a while to copy the structure...
Posted: Wed Nov 03, 2004 6:44 pm
by mudkicker
Hmm..
You mean that if don't reference and call two time addBlock function it' consumes more memory if we reference the argument and call twice it with addblock func. ?
Posted: Wed Nov 03, 2004 6:51 pm
by timvw
i mean that with php4:
function foo($object)
- you are manipulating a copy of the object,
- consumes memory to make a copy,
- consumes time to make a copy
function foo(&$object)
- manipulate the object directly
Posted: Wed Nov 03, 2004 6:54 pm
by mudkicker
ok, i think i got it.

thanks for your help tim.