How to fix FATAL ERROR Uncaught Error: Using $this when not in object context

This error “Using $this when not in object context” is pretty straightforward. The error generally occurs when you use $this in the non-static method. So let’s take an example to understand this.

<?php
class myclass {

    public $variable;

    public function __construct() {

        $this->variable = 'initialized';
    }

    public function myMethod() {
        return $this->variable;
    }

}

So whenever you execute this code, you will get one PHP warning and one fatal error.

WARNING Non-static method myclass::myMethod() should not be called statically on line number 17
FATAL ERROR Uncaught Error: Using $this when not in object context in

So what exactly the error is? So let check the myclass class. You can see there is a public variable called $variable. To initialize or get a value from a non-static variable we have to use $this->.

So in the construct() method, we have initialized $varibale like this $this->variable = ‘initialized’; . From myMethod() method will return the $variable. At end of the code, we write echo myclass::myMethod() which should print the word ‘initialized’.

But if we run this, we will get the above error. Here the first warning “Non-static method myclass::myMethod() should not be called statically” clearly tell you, as myMethod() is not a static function, you can’t use :: this.

So we have to make myMethod() function static or make an instance of this class like this.

$newClass = new myClass();
echo $newClass->myMethod(); //which will print initialized

Or you can make myMethod() as a static method. So you don’t have to instantiate the class. We can directly call the method by using Scope Resolution Operator(::). So the code will be like below-

<?php
class myclass {

    public static function myMethod() {
        return "initialized";
    }

}

echo myclass::myMethod();

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment