How do I check in PHP that I'm in a static context (or not)?

后端 未结 11 1302
时光说笑
时光说笑 2020-11-30 08:16

Is there any way I can check if a method is being called statically or on an instantiated object?

11条回答
  •  长情又很酷
    2020-11-30 09:20

    Test for $this:

    class Foo {
    
        function bar() {
            if (isset($this)) {
                echo "Y";
            } else {
                echo "N";
            }
        }
    }
    
    $f = new Foo();
    $f->bar(); // prints "Y"
    
    Foo::bar(); // prints "N"
    

    Edit: As pygorex1 points out, you can also force the method to be evaluated statically:

    class Foo {
    
        static function bar() {
            if (isset($this)) {
                echo "Y";
            } else {
                echo "N";
            }
        }
    }
    
    $f = new Foo();
    $f->bar(); // prints "N", not "Y"!
    
    Foo::bar(); // prints "N"
    

提交回复
热议问题