1.2.1406. Using $this Outside A Class

$this is a special variable, that should only be used in a class context.

Until PHP 7.1, $this may be used as an argument in a function or a method, a global, a static : while this is legit, it sounds confusing enough to avoid it. Starting with PHP 7.1, the PHP engine check thoroughly that $this is used in an appropriate manner, and raise fatal errors in case it isn’t.

Yet, it is possible to find $this outside a class : if the file is included inside a class, then $this will be recognized and validated. If the file is included outside a class context, it will yield a fatal error : Using `$this <https://www.php.net/manual/en/language.oop5.basic.php>`_ when not in object context.

<?php

function foo($this) {
    echo $this;
}

// A closure can be bound to an object at later time. It is valid usage.
$closure = function ($x) {
    echo $this->foo($x);
}

?>

See also Closure::bind and The Basics.

1.2.1406.1. Specs

Short name

Classes/UsingThisOutsideAClass

Rulesets

All, Analyze, Changed Behavior, CompatibilityPHP71, LintButWontExec

Exakat since

0.8.4

PHP Version

With PHP 7.0 and older

Severity

Critical

Time To Fix

Instant (5 mins)

Changed Behavior

PHP 7.1 - More

Precision

High

Features

$this

Note

This issue may lint but will not run

Available in

Entreprise Edition, Exakat Cloud