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 static variable

Description

$this is a special variable, automatically bound to the current object inside a method. It cannot be redefined, in particular by making it a static variable, which would give it a persistent value between calls and remove its automatic binding to the object.

This is checked at compile time, whether the method is ever called or not.

Example

<?php

class X {
    public function foo() {
        static $this;
    }
}

?>

Alternatives

  • Use another variable name for the static variable.
  • Store the required data in a property of the object instead.

Changed Behavior

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