Skip to content

Indicates whether a variable is global #4245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 2.1.x
Choose a base branch
from

Conversation

cedric-anne
Copy link

@cedric-anne cedric-anne commented Aug 15, 2025

This will permit to easilly assign types to global variables in an extension. Without this change, it is not possible to distinguish local variables from global variables.

Related to phpstan/phpstan#13243 and following a discussion in #4233.

Here is an exemple:

<?php

namespace MyPhpstanExtension;

use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ExpressionTypeResolverExtension;
use PHPStan\Type\Type;

class GlobalExpressionTypeResolverExtension implements ExpressionTypeResolverExtension
{

	public function getType(Expr $expr, Scope $scope): ?Type
	{
		if (!$expr instanceof Variable || !$scope->isGlobalVariable($expr->name)) {
			return null;
		}

		if ($expr->name === 'DB') {
			return new ObjectType(\App\Db::class);
		}

		return null;
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant