|
Posted by Lόpher Cypher on 12/30/05 03:12
Oli Filth wrote:
>
> I'm assuming you must be using PHP 4, because this works as you want it
> to in PHP 5.
>
> In PHP 4, objects are copied by value; in PHP 5, objects are copied by
> reference.
>
> To copy by reference in PHP 4, use &, i.e.:
>
> $global[0] =& $a;
>
True, this works if I assign it outside the object. The exact thing I am
trying to do is that I have a root class, from which every other class
inherits, and in its constructor I call a global function which is
supposed to "register" the new object. So, basically I have
global $global;
$global = array();
function reg(&$obj) {
global $global;
$global[count($global)] = &$obj;
}
class A {
var $a;
function A() {
$this->a = 0;
reg(&$this);
}
function inc() {
$this->a += 2;
}
}
This will not work:
$a = new A();
echo "$a->a ".$objs[0]->a."<br />";
$a->inc();
echo "$a->a ".$objs[0]->a."<br />";
$a->inc();
echo "$a->a ".$objs[0]->a."<br />";
outputs
0 0
2 0
4 0
If I make reg() a method of A, it also does not work, even if I call it
outside the object:
$a = new A(); // no reg() call
$a->reg();
echo "$a->a ".$objs[0]->a."<br />";
$a->inc();
echo "$a->a ".$objs[0]->a."<br />";
$a->inc();
echo "$a->a ".$objs[0]->a."<br />";
still outputs
0 0
2 0
4 0
Apparently, this does not work either:
$a = new A();
reg($a);
I guess I am missing something about references here.. :)
luph
Navigation:
[Reply to this message]
|