Skip to content

Free-standing binary op exressions should be treated as equivalent "if" expressions #2741

@muglug

Description

@muglug
function maybeString(): ?string {
    return rand(0, 10) > 4 ? "test" : null;
}

function test(): string {
    $foo = maybeString();
    ($foo !== null) || ($foo = "");
    return $foo;
}

is directly equivalent to

function maybeString(): ?string {
    return rand(0, 10) > 4 ? "test" : null;
}

function test(): string {
    $foo = maybeString();
    if (!($foo !== null)) {
        $foo = "";
    }
    return $foo;
}

Similarly,

function maybeString(): ?string {
    return rand(0, 10) > 4 ? "test" : null;
}

function test(): string {
    $foo = maybeString();
    ($foo === null) && ($foo = "");
    return $foo;
}

is directly equivalent to

function maybeString(): ?string {
    return rand(0, 10) > 4 ? "test" : null;
}

function test(): string {
    $foo = maybeString();
    if ($foo === null) {
        $foo = "";
    }
    return $foo;
}

https://phpstan.org/r/de46736e-f6da-495a-ad3d-a1484626dfeb and
https://phpstan.org/r/ae3b7244-1720-4bf5-8bf3-5222caf2dacf

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions