1.2.6. $this Is Not An Array

$this variable represents the current object and it is not an array.

This is unless the class (or its parents) has the ArrayAccess interface, or extends ArrayObject or SimpleXMLElement.

<?php

// $this is an array
class Foo extends ArrayAccess {
    function bar() {
        ++$this[3];
    }
}

// $this is not an array
class Foo2 {
    function bar() {
        ++$this[3];
    }
}

?>

See also ArrayAccess, ArrayObject and The Basics.

1.2.6.1. Suggestions

  • Extends ArrayObject, or a class that extends it, to use $this as an array too.

  • Implements ArrayAccess to use $this as an array too.

  • Use a property in the current class to store the data, instead of $this directly.

1.2.6.2. Specs

Short name

Classes/ThisIsNotAnArray

Rulesets

All, Analyze, Changed Behavior

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

High

Features

$this

Available in

Entreprise Edition, Exakat Cloud