开发者

weird php behaviour with classes and static methods

开发者 https://www.devze.com 2023-01-05 05:06 出处:网络
I maintain an application that uses a (to me) surprising PHP quirk/bug/feature. Consider this code: <?php

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() {
        pri开发者_开发百科nt_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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消