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

Viewed 16458

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

12 Answers

It's 2022 now, with php 7.4, 8: you can/should no longer be vague about the context a method will be called in.

If a method is not declared static, 7.4 will warn you, 8 will fatal error.

If a method is declared static, $this is never available.

<?php

class C {
   public function nonStaticMethod() {
      print isset($this) ? "instance ": "static\n";
   }
   public static function staticMethod() {
      print isset($this) ? "instance ": "static\n";
   }
}

// php 8: Fatal error: Uncaught Error: Non-static method Foo::bar() cannot be called statically
// php 7.4: Deprecated: Non-static method Foo::bar() should not be called statically
C::nonStaticMethod();

C::staticMethod();

$f = new C();
$f->nonStaticMethod();
// `$this` is still not defined. It works without the instance context,
// even though you called it from an instance.
$f->staticMethod();

Other hacks are available, of course.

Create a static variable and change it in the constructor.

private static $isInstance = false;

public function __construct()
{
    self::$isInstance = true;
}

Now you can check it

public function myMethod()
{
    if (self::$isInstance) {
        // do things
    }
}
Related