1.2.942. PHP Native Class Type Compatibility

PHP enforces the method compatibility with native classes and interfaces.

This means that classes that extends native PHP classes or interfaces must declare compatible types. They can’t omit typing, like it was the case until PHP 8.0. This is needed for compatibility with PHP 8.0. This is probably good for older versions too, although it is not reported.

The attribute ReturnTypeWillChange is taken into account by this rule. Note that it is not detected when auditing with PHP < 8.0, so it won’t have effect until this version. The attribute was declared in PHP 8.1, though it is also taken into account when auditing with PHP 8.0.

<?php

class a extends RecursiveFilterIterator {

    // fully declared method
    function hasChildren(): bool {
        return true;
    }

    // key() returns mixed. Omitting the type used to be quiet
    function key() {}

    //    #[\ReturnTypeWillChange] is taken into account

}
?>

See also method-compatibility.

1.2.942.1. Suggestions

  • Make sure the methods are compatible or identical to the parent’s method signature.

1.2.942.2. Specs

Short name

Php/NativeClassTypeCompatibility

Rulesets

All, Analyze, Changed Behavior, CompatibilityPHP81

Exakat since

2.2.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

High

Features

returntypewillchange, type-covariance, type-contravariance

Available in

Entreprise Edition, Exakat Cloud