1.2.339. Dependant Trait

Traits should be autonomous. It is recommended to avoid depending on methods or properties that should be in the using class.

The following traits make usage of methods and properties, static or not, that are not defined in the trait. This means the host class must provide those methods and properties, but there is no way to enforce this.

This may also lead to dead code : when the trait is removed, the host class have unused properties and methods.

<?php

// autonomous trait : all it needs is within the trait
trait t {
    private $p = 0;

    function foo() {
        return ++$this->p;
    }
}

// dependant trait : the host class needs to provide some properties or methods
trait t2 {
    function foo() {
        return ++$this->p;
    }
}

class x {
    use t2;

    private $p = 0;
}
?>

See also Dependant Abstract Classes.

1.2.339.1. Suggestions

  • Add local property definitions to make the trait independent

  • Make the trait only use its own resources

  • Split the trait in autonomous traits

1.2.339.2. Specs

Short name

Traits/DependantTrait

Rulesets

All, Analyze, Changed Behavior

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

High

Features

trait

Examples

Zencart

Available in

Entreprise Edition, Exakat Cloud