Ryan Hubbard writes:
I would like to use a static variable inside a method in an object to
hold a reference to another object. But i can't get it to work. Here
is an example
class B{
var $test;
}
class A{
function hold($a){
static $ref;
if(is_object($a)){
$ref = $a;
}
print $ref->test;
}
}
This one won't work because you are passing a copy of the object, not
a reference. The same code will work the way you expect in PHP5 where
the value copied by the assignment $ref = $a will be a handle
identifying the object rather than the object itself.
If i try passing it in as a refrence the second call gives nothing as
if it forgot about it.
class A{
function hold(&$a){
static $ref = 0;
if(is_object($a)){
$ref = &$a;
}
print $ref->test;
}
}
You might expect this one to work but it doesn't, because references
aren't pointers, and because of the way static variables are
implemented in PHP. "$ref = &$a" does not mean "$ref holds a
reference to $a" rather it means "$ref now references the same address
as $a". The consequence of this is that the symbol $ref no longer
references the static area of memory assigned to it when it was
declared. When you re-enter the function hold() the symbol $ref is
reinitialised to reference the same area of memory that it did in the
first call, which is unchanged.
The only way to preserve an object between calls is to copy it to the
area of memory assigned to $ref in the static declaration, as in your
first example. If hold() returns a reference then you can affect the
static value from outside the function that declared it.
Like this
class B{
var $test;
}
class A{
function &hold($a){
static $ref;
if(is_object($a)){
$ref = $a;
}
print $ref->test;
return $ref;
}
}
$a = new A;
$b = new B;
$b->test = 10;
$b =& $a->hold($b); // $b and $ref now reference the same area of memory.
$b->test = 11;
$a->hold(); // This will work now.
--
__o Alex Farran
_`\<,_ Analyst / Programmer
(_)/ (_)
www.alexfarran.com