[php] 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?

This question is related to php function class object fatal-error

The answer is


$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();

Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.


If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.

If you enable E_STRICT, PHP will raise a Notice about this:

Strict Standards: 
Non-static method foobar::foobarfunc() should not be called statically

Do this instead

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

On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.


It seems to me to be a bug in PHP. The error

'Fatal error: Uncaught Error: Using $this when not in object context in'

appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:

Class_Name
{
    function foo()
    {
        $this->do_something(); // The error appears there.
    }
    function do_something()
    {
        ///
    }
}

While the error is here:

Class_Name::foo();

When you call the function in a static context, $this simply doesn't exist.

You would have to use this::xyz() instead.

To find out what context you're in when a function can be called both statically and in an object instance, a good approach is outlined in this question: How to tell whether I’m static or an object?


Fast method : (new foobar())->foobarfunc();

You need to load your class replace :

foobar::foobarfunc();

by :

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

or :

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

Or make static function to use foobar::.

class foobar {
    //...

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

First you understand one thing, $this inside a class denotes the current object.
That is which is you are created out side of the class to call class function or variable.

So when you are calling your class function like foobar::foobarfunc(), object is not created. But inside that function you written return $this->foo(). Now here $this is nothing. Thats why its saying Using $this when not in object context in class.php

Solutions:

  1. Create a object and call foobarfunc().

  2. Call foo() using class name inside the foobarfunc().


You are calling a non-static method :

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

Using a static-call :

foobar::foobarfunc();

When using a static-call, the function will be called (even if not declared as static), but, as there is no instance of an object, there is no $this.

So :

  • You should not use static calls for non-static methods
  • Your static methods (or statically-called methods) can't use $this, which normally points to the current instance of the class, as there is no class instance when you're using static-calls.


Here, the methods of your class are using the current instance of the class, as they need to access the $foo property of the class.

This means your methods need an instance of the class -- which means they cannot be static.

This means you shouldn't use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :

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


For more informations, don't hesitate to read, in the PHP manual :


Also note that you probably don't need this line in your __construct method :

global $foo;

Using the global keyword will make the $foo variable, declared outside of all functions and classes, visibile from inside that method... And you probably don't have such a $foo variable.

To access the $foo class-property, you only need to use $this->foo, like you did.


Just use the Class method using this foobar->foobarfunc();


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to fatal-error

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes) PHP Notice: Undefined offset: 1 with array when reading data PHP Fatal error: Cannot access empty property PHP Fatal error when trying to access phpmyadmin mb_detect_encoding Fatal error: Class 'SoapClient' not found Cannot redeclare function php C++ Fatal Error LNK1120: 1 unresolved externals A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...? relative path in require_once doesn't work