Skip to content

Feature request: add syntax to prevent preprocessing #20638

@woodholly

Description

@woodholly

Description

The Problem:

$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:

if ($logger->isHandling(Logger::DEBUG)) {
    $logger->debug('action', $expensiveStuff);
}

Closure - can't capture locals cleanly:

$logger->debug('action', fn() => ['user' => $user, 'x' => $x, 'y' => $y]);

Short-circuit - inverted logic, looks like a bug, globals:

$noDebug or $logger->debug('action', $expensive);

So, last hope - build postprocessor to remove debug ? - are we writing C?

Proposed: lazy Keyword

function debug(string $msg, lazy array $context = []): void {
    if (!$this->enabled) return;  // $context never evaluated
    $this->write($msg, $context); // evaluated here
}

Usage stays clean:

$logger->debug('action', ['trace' => debug_backtrace()]);

Other Use Cases

assert(lazy $obj->isValid(), lazy $obj->getErrorMessage());
$cache->remember('key', lazy $this->heavyQuery());

Kotlin, Swift, Scala, Rust all have this. PHP doesn't.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions