Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 $this directly inside the method, without importing it as global.
  • Pass the object as a parameter to the function that needs it.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See