View Single Post

  #3 (permalink)  
Old 09-03-2004
MRe
 
Posts: n/a
Default Re: PHP memory management

Hi, thank you for the reply,

One thing I forgot to mention, it's PHP 4, Apache (errm, version ?), on
Linux

> I'm curious for your code... Care to show an example of what causes your
> trouble?


One example coming up (hopefully a good one), it didn't go down too well...

(please note, I had to copy this code _by hand_ from test code I wrote on
the ol' laptop. If there are any compile errors in here, sorry, it is
compile error free on the laptop. I guess I could have copied the code
across on a floppy, but the floppy drive is on the other side of the room,
I'd have to stand up!)

class fun
{

var $callbacks;
var $test;

function fun()
{ $this->test = 1;
$this->callbacks = array();
array_push($this->callbacks, array($this, "fun1"));
$this->test = 5;
}

function test()
{ call_user_func($this->callbacks[0]);
}

function fun1()
{ echo($this->test."\n");
}

}

$fun = new fun;
$fun->test();

....I had expected this to output 5, but it output 1 (I assume it copied the
class at... array($this ...before executing... $this->test = 5.
....Fixed with...

$callback = array();
$callback[0] = &$this;
$callback[1] = "fun1";
array_push($this->callbacks, $callback);

....And it works (outputting 5), further testing had me modifying the test
function like this...

function test()
{ $this->test = 10;
call_user_func($this->callbacks[0]);
}

....and lo and behold, it outputs 5, the bastard! I tracked this down to
the... new ...call, which changing to...

$fun = &new fun;

....fixes the problem (outputs 10) (I assume it created one instance of the
class, called the constructor, returned, copying it, from new, and stored
the copy in $fun, and as such, when... call_user_func($this->callbacks[0]);
....is executed, the class referred to by... callbacks[0] ...is the original
copy (not the copied copy which had the... $this->test = 10; ...executed in
it); is any of this making any sence)

> Ehhh, you do know that all memory used by the script is (supposed to be)
> released when the script ends?


Whether I know that or not, I do now. But still, I don't like being at the
mercy of the language; it thinks just because it cleans up after itself,
that it's allowed to create as much clutter as it wants, copying arrays and
objects and the likes every-which-way. I would be turning in my grave, if
only I were dead.

All I want to know is that when I access an object, that it's the one I
created, and not a copy of an imitation. As they say, 'A mere copier of
$this can never produce anything great'

Thanks again,
MRe


Reply With Quote