Check if a php method is called statically or as an instance method

PHP allows to call you any method of a class both as static and as instance method. Recent version of PHP is more strict though. But still you can call non-static function as static. Calling a non-static function that uses $this statically will cause a fatal error. You’d ¬†want to catch this and throw exception with meaningful message.

If you can determine how this method is called whether statically or as instance method you can handle this situation.

See this example class.

class C {
    private $value = "value";
    public function method () { 
        echo __METHOD__. "\n"; 
        echo "Value:". $this->value. "\n"; 
    }
}

This method will raise a fatal error you if call it as C::method().

To determine if its this is called statically or as an instance method there are two techniques.

  1. Using debug_backtrace
    1. class A { 
       public function m(){ 
       $bt = debug_backtrace(); 
       if($bt[0]['type']=='::')
       throw new Exception(__METHOD__." is called statically");
       }
      }
      
      
  2. Using isset on $this.
    1. class A { 
       public function m(){ 
       if(!isset($this))
       throw new Exception(__METHOD__." is not called from class instance");
       }
      }

 

The last one is shorter. But first one is more explicit.

Author: shiplu

The Lone Explorer.

1 thought on “Check if a php method is called statically or as an instance method”

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve * Time limit is exhausted. Please reload the CAPTCHA.