Skip to content

Detect variable type when passing it by reference #3504

@8749236

Description

@8749236

Feature description or problem with existing feature
Given following code, Intelephense belives variable $value is of type null and produce warning when passed to other methods.

<?php

declare(strict_types=1);

function try_get_value(int $key, string &$output): bool {
    $output = "test value";
    return true;
}

function print_string(string $str): void {
    echo $str . PHP_EOL;
}

try_get_value(1234, $value);
print_string($value);

Error:

Expected type 'string'. Found 'null'.

Describe the solution you'd like
The Intelephense should recognize that the $value is used as an output variable thus should have the same type as the parameter, it should have type string.

Additional context
This enables "try_xxx" pattern which can be used to avoid returning nullables and allow better code semantics like:

if ($dictionary->try_get_value("email")) {
    // do something
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions