Skip to content

Commit a17afaa

Browse files
committed
Clarify documentation on void callback contracts, distinguishing between native PHP : void syntax and PHPDoc @return void contracts, with examples for better understanding.
1 parent 3074add commit a17afaa

1 file changed

Lines changed: 16 additions & 3 deletions

File tree

‎docs/supported-types/callables-and-closures.md‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,24 @@ This ensures that invoking `$container->factory(...)` enforces runtime parameter
5555

5656
## Discarded Returns in `void` Callback Contracts (`callable(): void`)
5757

58-
In native PHP functions and methods, a `: void` return typehint strictly forbids returning any value, throwing a `TypeError` if a value is returned.
58+
It is important to distinguish between **native PHP `: void` typehint syntax** and **PHPDoc `@return void` contracts**:
5959

60-
However, for **callables and closures annotated with `callable(): void` or `Closure(): void`**, TypePHP **discards the return value rather than throwing a `TypeError`**.
60+
### Native PHP `: void` Syntax (PHP Language Level)
6161

62-
This behavior ensures seamless compatibility with PHP short arrow functions (`fn() => $expr`), which always implicitly return the evaluated result of their expression:
62+
When a function or closure explicitly declares native PHP `: void` return syntax (`function(): void`), PHP's Zend Engine strictly forbids returning any value at the language level. Attempting to return a value results in a native PHP compile error:
63+
64+
```php
65+
// Native PHP ': void' syntax
66+
$func = function (int $a): void {
67+
return $a; // Native PHP Fatal Error: A void function must not return a value
68+
};
69+
```
70+
71+
### PHPDoc `@return void` Contracts (TypePHP Level)
72+
73+
For callbacks and closures annotated with **PHPDoc `@return void`** (e.g. `callable(): void` or `Closure(): void`), TypePHP **discards the return value rather than throwing a `TypeError`**.
74+
75+
This design behavior ensures full compatibility with PHP short arrow functions (`fn() => $expr`), which always implicitly return the evaluated result of their expression:
6376

6477
```php
6578
class User

0 commit comments

Comments
 (0)