Cannot use $this as global variable
Description
The pseudo-variable $this is automatically available inside every method of a class, and refers to the current object. It is not possible to import $this into the global symbol table using the global keyword. $this is special and not a regular variable that may be made global.
Example
<?php
class X {
function foo() {
global $this;
}
}
(new X)->foo();
?>
Alternatives
- Use
$thisdirectly inside the method, without importing it as global. - Pass the object as a parameter to the function that needs it.
Related error messages
- cannot-re-assign-$this
- using-$this-when-not-in-object-context
- cannot-use-auto-global-as-lexical-variable
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See