Skip to content

Report error for non-nullable typed parameters with null as default value #702

@Majkl578

Description

@Majkl578

This is a feature request to abolish legacy syntax:

public function bar(int $baz = null): void

this code should contain proper and explicit nullable type:

public function bar(?int $baz = null): void

https://phpstan.org/r/ebb01a22d284b66db7a131b376fe821c - no errors

This code is currently functionally valid, both in PHP and PHPStan. But it's broken semantically. Making the type nullable by assigning null as default value should be considered a bug in 7.1+, it has ever appeared only because 7.0 had no nullable types.

I have already had multiple discussions about this with multiple people. Basically the concensus has always been in favor of explicit nullable since omitting it may introduce unintended LSP violations, especially in inheritance (i.e. you change default value from null to a number in a subclass and end up with violated LSP).

I know this can be done i.e. by CodeSniffer (Slevomat CS has a sniff aleady), but I think this should be checked in PHPStan (as well).
It should probably go somewhere around level 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions