reference problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

reference problem

Post 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..)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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...
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post 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. ?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

ok, i think i got it. :) thanks for your help tim.
Post Reply