1.2.1460. Wrong Typed Property Default

Property is typed, yet receives an incompatible value at constructor time.

Initialized type might be a new instance, the return of a method call or an interface compatible object.

PHP compiles such code, but won’t execute it, as it detects the incompatibility at execution time.

<?php

class X {
    private A $property;
    private B $incompatible;

    function __construct() {
        // This is compatible
        $this->property = new A();

        // This is incompatible : new B() expected
        $this->incompatible = new C();

    }
}

?>

See also Wrong Type Returned and Mismatch Type And Default.

1.2.1460.2. Connex PHP features

1.2.1460.2.1. Suggestions

  • Remove the type hint of the property

  • Fix the initialization call

  • Use an interface for typehint

1.2.1460.2.2. Specs

Short name

Classes/WrongTypedPropertyInit

Rulesets

All, Analyze, CE, CI-checks, Class Review, LintButWontExec

Exakat since

2.0.9

PHP Version

With PHP 7.4 and more recent

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Note

This issue may lint but will not run

Available in

Entreprise Edition, Community Edition, Exakat Cloud