MyBB Community Forums

Full Version: Freaky PHP Behavior
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I thought this was odd.

Let's say we have some classes:

class A
{
    function B {
           static $i = 0;
           $i++;
           if (condition) self::B();
     }
}

Everytime B is called, you'd expect $i to increase as such: 0,1,2,3,etc.

Now, throw this in:

class C extends A
{
       function foo()
       {
            self::B();
       }
}

Say you start off with foo() and B ends up being called five times, and you print $i before you increment it. What do you expect to show up? 0,1,2,3,4,5 right? Well, this is actually what shows up: 0,0,1,2,3,4.

See, the thing is that B is a static function; A has one, but since C extends A, C has one as well. And they're separate. First $i belongs to C, then the rest of the time it belongs to A. The self::B will always call A's function, regardless of whatever first called B.

Apparently this is fixed in v5.3.

I just thought someone would find this as interesting as I did.
Wow, that's weird. O_o Glad that's fixed.
It sure is weird, but I don't think I've ever had to use anything like tat anyway (so far) xD
The fix is really more of a hack:

New in 5.3 is the static keyword - like self and parent. So if you change the code to be

if (condition) static::B();

then it's always the first class's B that gets called.