Skip to content

gettype narrow call and match use #13972

Open
phpstan/phpstan-src
#6383

Description

@jaugustin

Bug report

Hello,

I was hoping phpstan to narrow type of a variable after using gettype and a match on the type

(maybe it's a feature request)

class HelloWorld
{
	public function getAssignment(string $flagKey, string|bool $defaultValue): string|bool
    {
            $type = gettype($defaultValue);

            return match ($type) {
                'string' => $this->getString($defaultValue),
                'boolean' => $this->getBool($defaultValue),
            };
    }

	public function getBool(bool $default): bool {
		return true;
	}

	public function getString(string $default): string {
		return "toto";
	}
}

Code snippet that reproduces the problem

https://phpstan.org/r/1c8f8061-3da3-485a-939a-591027f2b65f

Expected output

it should not detect error in the snipet

Did PHPStan help you today? Did it make you happy in any way?

No response

Activity

  1. staabm commented on Jan 21, 2026

    @staabm
    Contributor

    as a workaround: if you use match (gettype($defaultValue)) it works like you expect it.
    we currently don't get the right type in this case, when there is a variable involved

    https://phpstan.org/r/650d4f21-1e56-4993-bb01-1ef83f3db410

  2. ondrejmirtes commented on Feb 10, 2026

    @ondrejmirtes
    Member

    This could be done. Analysing $type = gettype($defaultValue); could create ConditionalExpressionHolder in the sense: "if $type is 'string' then $defaultValue is string.

  3. added this to the Dependent types milestone on Feb 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions