[php-src] Issue #20638: Feature request: add syntax to prevent preprocessing
[email protected] (woodholly)
| Newsgroups | php.bugs |
|---|---|
| Message-ID | <kSOlOslyLe0x9T0slZhHOL5EM05NzDcybU3in19gz2w@main.internal.php.net> |
Issue: https://github.com/php/php-src/issues/20638
Author: woodholly
### Description
The Problem:
```php
$logger->debug('action', [
'user' => $user->toArray(),
'trace' => debug_backtrace(),
]);
```
That debug_backtrace() runs every time, eats CPU, RAM, even when debug is off. PHP evaluates arguments before the call. Always.
Current Workarounds Suck:
```php
if ($logger->isHandling(Logger::DEBUG)) {
$logger->debug('action', $expensiveStuff);
}
```
Closure - can't capture locals cleanly:
```php
$logger->debug('action', fn() => ['user' => $user, 'x' => $x, 'y' => $y]);
```
Short-circuit - inverted logic, looks like a bug, globals:
```php
$noDebug or $logger->debug('action', $expensive);
```
So, last hope - build postprocessor to remove debug ? - are we writing C?
Proposed: lazy Keyword
```php
function debug(string $msg, lazy array $context = []): void {
if (!$this->enabled) return; // $context never evaluated
$this->write($msg, $context); // evaluated here
}
```
Usage stays clean:
```php
$logger->debug('action', ['trace' => debug_backtrace()]);
```
Other Use Cases
```php
assert(lazy $obj->isValid(), lazy $obj->getErrorMessage());
$cache->remember('key', lazy $this->heavyQuery());
```
Kotlin, Swift, Scala, Rust all have this. PHP doesn't.