1.2.320. Cyclic References

Avoid cyclic references.

Cyclic references happen when an object points to another object, which reciprocate. This is particularly possible with classes, when the child class has to keep a reference to the parent class. Cyclic references, or circular references, are memory intensive : only the garbage collector can understand when they may be flushed from memory, which is a costly operation. On the other hand, in an acyclic reference code, the reference counter will know immediately know that an object is free or not.

<?php

class a {
    private $p = null;

    function foo() {
        $this->p = new b();
        // the current class is stored in the child class
        $this->p->m($this);
    }
}

class b {
    private $pb = null;

    function n($a) {
        // the current class keeps a link to its parent
        $this->pb = $a;
    }
}
?>

See also About circular references in PHP and A Journey to find a memory leak.

1.2.320.1. Suggestions

  • Use a different object when calling the child objects.

  • Refactor your code to avoid the cyclic reference.

1.2.320.2. Specs

Short name

Classes/CyclicReferences

Rulesets

All, Analyze, Class Review

Exakat since

2.1.3

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

class, extends

Available in

Entreprise Edition, Exakat Cloud