Page 1 of 1
OOP, static variables in methods.
Posted: Sat Feb 03, 2007 10:47 am
by bokehman
Code: Select all
<?php
class myClass
{
function myMethod($in = null)
{
static $i = 0;
!$in or $i++;
echo $i;
}
}
$class = new myClass();
$class->myMethod();
$class->myMethod(1);
$class2 = new myClass();
$class2->myMethod();
$class2->myMethod(1);
$class3 = new myClass();
$class3->myMethod();
$class3->myMethod(1);
?>
That prints:
Is that the expected bahaviour or a bug? I thought each new object was unique and nothing going on in another object should affect it but this shows that is not the case.
Any thoughts on this?
Posted: Sat Feb 03, 2007 10:56 am
by Ollie Saunders
The phenomenon is called "early binding of local statics" or something like that.
its not a bug, its PHP; it's not a particularly great feature, many would prefer late binding instead; it may be changed to late binding for PHP 6.
Posted: Sat Feb 03, 2007 11:05 am
by bokehman
ole wrote:it may be changed to late binding for PHP 6.
Well that would be even worse because the script would become version dependant.
Posted: Sat Feb 03, 2007 11:20 am
by bokehman
Now you have given me that bit of info I have found "Early binding" and "Static variables" are synonomous as are "Late binding" and "Dynamic variables" the difference being "Static variables" are read in at compile time rather than run time.