tags:

views:

52

answers:

2

I maintain an application that uses a (to me) surprising PHP quirk/bug/feature. Consider this code:

<?php
class Bar {
    // called statically
    public function doStuff() {
        print_r($this);
    }
}

class Foo {
    public function main() {
        Bar::doStuff();
    }
}

$foo = new Foo();
$foo->main();

Running on PHP 5.2.x, the output is:

Foo Object ( ) 

That means, although Bar::doStuff() is called statically, it still has access to $this where $this is a reference to the object that called Bar::doStuff(). Never came across that behaviour until recently. Quite evil to rely on this in production code if you ask me.

If you add a static and change the method signature to public static function doStuff() it throws a E_NOTICE: Undefined variable: this - which seems right to me.

Anyone has an explanation for this behaviour?

+4  A: 

In PHP 5.3 at least, you get a strict warning:

PHP Strict Standards: Non-static method Bar::doStuff() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 11

And quite rightfully so.

janmoesen
Thanks for the hint, then I know which application I wont upgrade to PHP 5.3 any time soon...
Max
@Max This has nothing to do with the PHP Version. Use `error_reporting(-1)` to enable all errors, including `E_STRICT`. Will raise on PHP < 5.3 too
Gordon
There are some (old) bugs reported on this: #12622 or #20089 for example. I especially like hellys comment 2004 in #20089 ... although couldn't find any change notes that "fixes" this behavior between 5.2.x and 5.3 ..
Kuchen
A: 

It might be best to create some type of Printable_Object class and simply inherit from that. Add the doStuff() method to that class, and use the inherited method properly.

Marcus Adams