Using $this inside a static function fails

Using $this inside a static function is not allowed in PHP because the $this variable is only available within the context of a non-static method. A static method is called on a class, rather than an instance of the class, so there is no object context for $this to refer to.

Watch a course Learn object oriented PHP

Here's an example of a class with a static and a non-static method:

<?php

class MyClass
{
  public static function staticMethod()
  {
    // Using $this here will result in an error
  }

  public function nonStaticMethod()
  {
    // Using $this here is valid
  }
}

If you need to access a property or method of the class within a static method, you can use the self keyword or the name of the class.

<?php

class MyClass
{
  public static function staticMethod()
  {
    self::nonStaticMethod();
    MyClass::nonStaticMethod();
  }

  public function nonStaticMethod()
  {
    echo "I am nonStaticMethod";
  }
}

You can see above examples, calling nonStaticMethod inside staticMethod using self keyword or class name.