Benjamin Crozat The web developer life

"Using $this when not in object context." Here's the fix.

Benjamin Crozat Benjamin Crozat1 minute read

Before you start reading this article, did you know 76 persons subscribed to my newsletter?

Join them and enjoy free content about the art of crafting websites!

"Using $this when not in object context." Here's the fix.
Table of contents

The “Using $this when not in object context” error occurs because you are calling a non-static method from a static method.

To fix it, make your static method non-static and call it from an object.

How to fix “Using $this when not in object context”, step by step

Take this code and try to run it to see “Using $this when not in object context” for yourself.

class Foo {
public static function bar() {
$this->baz();
}
 
public function baz() {
}
}
 
Foo::bar();

As you can see, we are trying to call baz(), which is a non-static method, from a static method.

As mentionned above, we need to:

  1. Remove the static keyword from bar()’s declaration;
  2. Create an instance of Foo and call bar() from there.
class Foo {
- public static function bar() {
+ public function bar() {
$this->baz();
}
 
public function baz() {
}
}
 
-Foo::bar();
+$foo = new Foo;
+$foo->bar();

Other posts to read

Whether PHP is dead or not is a matter of numbers, not opinions. I will provide you with essential statistics that will lead you to make better decisions.

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP.

Here's a case study for my blog in the programming niche, where I share everything I did to increase clicks by a huge amount since the beginning.

Learn why the "Invalid argument supplied for foreach()" warning happens, and let me show you multiple ways to fix it.

Learning a framework can be overwhelming. Time and practice will make you a master. Here are some best practices to help you toward your goal.

Learn why and how to fix "Methods with the same name as their class will not be constructors in a future version of PHP" warnings.

To keep getting better with PHP, you should subscribe to as many quality blogs as possible. In this article, I share the ones I often read myself.

Choose your web hosting provider and deploy your next Laravel project quickly and without any DevOps cost.

Laravel Dropbox Driver is a new storage you can add to your Laravel application and use it for all sorts of things.

Knowing which Laravel version you are running is important before you start writing code on a new project. There are multiple ways to do so.