Recent Posts

Showing posts with label context. Show all posts
Showing posts with label context. Show all posts

How to solve: Fatal error: Using $this when not in object context

$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.
This error can occur:
  1. If a non-static method is called statically. Example:
    class Foo {
       protected $var;
       public function __construct($var) {
           $this->var = $var;
       }
    
       public static function bar () {
           // ^^^^^^
           echo $this->var;
           //   ^^^^^
       }
    }
    
    Foo::bar();
    How to fix: review your code again, $this could only used in object context, and should never in a static method. And also, static method should not access the non-static property. Use self::$static_property to access the static property.
  2. If code from a class method has been copied over into a normal function or just the global scopeand keeping the $this special variable.
    How to fix: Review the code and replace $this with a different substitution variable.