"PHP Fatal Error: Using $this When Not in Object Context" Solved
Encountering the error "Fatal error: Using $this when not in object context" indicates that the referenced $this keyword is used outside a class context. To understand this better, let's dissect your code:
In your index.php, you require the load.php file, which in turn requires the class.php. Within class.php, the error occurs due to the $this->foo assignment in the constructor.
The line $this->foo = $foo; attempts to access the foo property of the current object, but without instantiating an object, there is no $this to refer to. Thus, this line is invalid outside an object context.
To rectify the error, you must instantiate an object of the foobar class and call its methods on that object. This can be achieved through the following examples:
Static Method Invocation:
Modify your class.php by declaring the foobarfunc method as static and defining a static variable $foo. This allows you to directly call the method without instantiating an object.
Object Invocation:
Instantiate an object of the foobar class using $foobar = new foobar; and then call its methods on that object using $foobar->foobarfunc();.
Therefore, the error arises when attempting to use $this outside an object context. To resolve it, either use static methods without $this reference or instantiate an object and call methods on it.
The above is the detailed content of Why Am I Getting the 'PHP Fatal Error: Using $this When Not in Object Context' Error?. For more information, please follow other related articles on the PHP Chinese website!