Search code examples
phpfunctionclassobjectfatal-error

PHP Fatal error: Using $this when not in object context


I've got a problem:

I'm writing a new WebApp without a Framework.

In my index.php I'm using: require_once('load.php');

And in load.php I'm using require_once('class.php'); to load my class.php.

In my class.php I've got this error:

Fatal error: Using $this when not in object context in class.php on line ... (in this example it would be 11)

An example how my class.php is written:

class foobar {

    public $foo;

    public function __construct() {
        global $foo;

        $this->foo = $foo;
    }

    public function foobarfunc() {
        return $this->foo();
    }

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

In my index.php I'm loading maybe foobarfunc() like this:

foobar::foobarfunc();

but can also be

$foobar = new foobar;
$foobar->foobarfunc();

Why is the error coming?


Solution

  • In my index.php I'm loading maybe foobarfunc() like this:

     foobar::foobarfunc();  // Wrong, it is not static method
    

    but can also be

    $foobar = new foobar;  // correct
    $foobar->foobarfunc();
    

    You can not invoke the method this way because it is not a static method.

    foobar::foobarfunc();
    

    You should instead use:

    $foobar->foobarfunc();
    

    If however, you have created a static method something like:

    static $foo; // your top variable set as static
    
    public static function foobarfunc() {
        return self::$foo;
    }
    

    then you can use this:

    foobar::foobarfunc();