1.2.1449. 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.1449.1. Suggestions

  • Remove the type hint of the property

  • Fix the initialization call

  • Use an interface for typehint

1.2.1449.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

Features

default-value

Note

This issue may lint but will not run

Available in

Entreprise Edition, Community Edition, Exakat Cloud