|
1 | 1 | # Inline Variables (`@var`) |
2 | 2 |
|
3 | | -While parameter and return contracts protect function boundaries, inline `@var` annotations enforce type safety on local variable assignments and reassignments inside function bodies or php file execution lines. |
| 3 | +While parameter and return contracts protect function boundaries, inline `@var` annotations enforce type safety on local variable assignments, reassignments, and direct return statements inside function bodies or PHP scripts. |
4 | 4 |
|
5 | 5 | --- |
6 | 6 |
|
@@ -43,7 +43,7 @@ TypePHP supports both single-variable single-line docblocks and multi-variable d |
43 | 43 | $id = 100; |
44 | 44 |
|
45 | 45 | /** @var non-empty-string $name -> single-line docblock */ |
46 | | -$name = 'Reymart' |
| 46 | +$name = 'Reymart'; |
47 | 47 | ``` |
48 | 48 |
|
49 | 49 | ### Multi-Variable Annotation (Array Destructuring) |
@@ -79,6 +79,33 @@ Both `/** @var positive-int $count */` and `/** @var positive-int */` behave ide |
79 | 79 |
|
80 | 80 | --- |
81 | 81 |
|
| 82 | +## Inline `@var` on Direct Return Statements |
| 83 | + |
| 84 | +You can place `/** @var Type */` directly above a `return` statement to perform surgical, expression-level type assertion narrowing inside function bodies, closures, or specific conditional branches: |
| 85 | + |
| 86 | +```php |
| 87 | +function fetchUserScores(): array |
| 88 | +{ |
| 89 | + /** @var list<positive-int> */ |
| 90 | + return [10, 20, 30]; // Valid |
| 91 | +} |
| 92 | + |
| 93 | +function fetchBadScores(): array |
| 94 | +{ |
| 95 | + /** @var list<positive-int> */ |
| 96 | + return [10, -5, 30]; // Throws TypeError on -5! |
| 97 | +} |
| 98 | + |
| 99 | +$getUser = function () use ($repo) { |
| 100 | + /** @var array{id: positive-int, username: non-empty-string} */ |
| 101 | + return $repo->fetchRawUser(); |
| 102 | +}; |
| 103 | +``` |
| 104 | + |
| 105 | +> **PHPStan & Psalm Parity:** Static analysis tools treat `/** @var Type */ return $expr;` as an inline type cast assertion. TypePHP physically enforces this assertion at runtime, ensuring that live dynamic returns strictly satisfy the annotated type. |
| 106 | +
|
| 107 | +--- |
| 108 | + |
82 | 109 | ## Block-Level Scope Isolation & Shadowing |
83 | 110 |
|
84 | 111 | TypePHP tracks variable type contracts using **Lexical Block Scope Frames**. |
@@ -146,4 +173,4 @@ You can enable or disable specific categories of inline variable validation in ` |
146 | 173 | 'arrays' => true, // Array shapes and lists (array{id: int}, list<T>) |
147 | 174 | 'objects' => true, // Class instance checks (@var User $user) |
148 | 175 | ], |
149 | | -``` |
| 176 | +``` |
0 commit comments