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

后端 未结 11 1266
时光说笑
时光说笑 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:13

    I actually use this line of code on all my scripts,it works well and it prevents errors.

    class B{
          private $a=1;
          private static $static=2;
    
          function semi_static_function(){//remember,don't declare it static
            if(isset($this) && $this instanceof B)
                   return $this->a;
            else 
                 return self::$static;
          }
    }
    

    The use of instanceof is not paranoia:

    If class A call class B statically function $this may exist on the A scope; I know it's pretty messed up but php does it.

    instanceof will fix that and will avoid conflicting with classes that may implement your "semi-static" functions.

    0 讨论(0)
  • 2020-11-30 09:19
    <?
    
    class A {
        function test() {
                echo isset($this)?'not static':'static';                                }
    
    }
    
    $a = new A();
    $a->test();
    A::test();
    ?>
    

    Edit: beaten to it.

    0 讨论(0)
  • 2020-11-30 09:20

    Checking if $this is set won't work always.

    If you call a static method from within an object, then $this will be set as the callers context. If you really want the information, I think you'll have to dig it out of debug_backtrace. But why would you need that in the first place? Chances are you could change the structure of your code in a way so that you don't.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-30 09:21

    Just return the class as new within the function.

    return new self();
    
    0 讨论(0)
提交回复
热议问题