1.2.66. Avoid Self In Interface

Self and Parent are tricky when used in an interface.

self refers to the current interface or its extended parents : as long as the constant is defined in the interface family, this is valid. On the other hand, when self refers to the current class, the resolution of names would happen at execution time, leading to undefined errors.

self may be used for typing : then, argument types in the host class must use the interface name, and can’t use self nor the class name, for compatibility reason. self can be used for returntype, as expected.

parent has the same behavior than self, except that it cannot be used inside an interface. This is one of those error that lint but won’t execute in certain conditions : namely, when a class implements the interface with parent, but has no parent by itself. This is now a dependency to the host class.

static can’t be used in an interface, as it needs to be resolved at call time.

<?php

interface i extends ii {
    // This 'self' is valid : it refers to the interface i
    public const I = self::I2 + 2;

    // This 'self' is also valid, as it refers to interface ii, which is a part of interface i
    public const I2 = self::IP + 4;

    // This makes interface i dependant on the host class
    public const I3 = parent::A;

    // This makes interface i dependant on the host class, where X must be defined.
    // It actually yields an error :  Undefined class constant 'self::I'
    public const I4 = self::X;
}

class x implements k {
    const X = 1;
}
?>

See also Scope Resolution Operator (::).

1.2.66.1. Suggestions

  • Use a fully qualified namespace instead of self

  • Use a locally defined constant, so self is a valid reference

1.2.66.2. Specs

Short name

Interfaces/AvoidSelfInInterface

Rulesets

All, Changed Behavior, Class Review, LintButWontExec

Exakat since

1.5.4

PHP Version

All

Severity

Critical

Time To Fix

Slow (1 hour)

Precision

Very high

Features

self, interface

Note

This issue may lint but will not run

Available in

Entreprise Edition, Exakat Cloud