Skip to content

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

When a function or method is declared to return by reference (e.g. public function &getString(): string), its return value is a valid lvalue that can be passed to a by-reference parameter. PHPStan was incorrectly reporting "expects variables only" for these cases.

Changes

  • Added callReturnsByReference() private method to src/Rules/FunctionCallParametersCheck.php that checks if an argument expression is a call to a function/method that returns by reference
  • Handles MethodCall, StaticCall, and FuncCall AST node types
  • Injected ReflectionProvider into FunctionCallParametersCheck constructor for resolving function reflections (method reflections are resolved via Scope::getMethodReflection())
  • Updated all ~20 test files that manually instantiate FunctionCallParametersCheck to pass the new ReflectionProvider parameter
  • Added documentation to CLAUDE.md about FunctionCallParametersCheck patterns

Root cause

FunctionCallParametersCheck only allowed variables, array dim fetches, property fetches, and static property fetches as valid by-reference arguments. It did not consider that function/method calls returning by reference also produce valid lvalues. The fix checks the called function/method's returnsByReference() reflection before reporting the error.

Test

Added tests/PHPStan/Rules/Functions/data/bug-757.php with test cases covering:

  • Instance method returning by reference (no error)
  • Instance method NOT returning by reference (error expected)
  • Static method returning by reference (no error)
  • Function returning by reference (no error)
  • Function NOT returning by reference (error expected)

Fixes phpstan/phpstan#757

…ef args

- Functions and methods that return by reference (declared with &) produce
  valid lvalues that can be passed to by-reference parameters
- Added callReturnsByReference() helper to FunctionCallParametersCheck that
  resolves reflection for MethodCall, StaticCall, and FuncCall nodes and
  checks returnsByReference()
- Injected ReflectionProvider into FunctionCallParametersCheck for resolving
  function reflections
- New regression test in tests/PHPStan/Rules/Functions/data/bug-757.php
@ondrejmirtes ondrejmirtes force-pushed the create-pull-request/patch-jtunz4a branch from 79858b8 to 2c92101 Compare February 12, 2026 14:42
@ondrejmirtes ondrejmirtes merged commit c5a9df5 into 2.1.x Feb 12, 2026
343 of 348 checks passed
@ondrejmirtes ondrejmirtes deleted the create-pull-request/patch-jtunz4a branch February 12, 2026 14:52
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.

Incorrect warning when using functions that return a reference

2 participants