Re: RFC: Marking return values as important (#[\NoDiscard])

From: Date: Thu, 13 Feb 2025 10:21:22 +0000
Subject: Re: RFC: Marking return values as important (#[\NoDiscard])
References: 1  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Wed, Jan 29, 2025 at 4:14 PM Tim Düsterhus <[email protected]> wrote:

> Hi
>
> Volker and I would like to start discussion on our RFC to allow "Marking
> return values as important (#[\NoDiscard])".
>
> Please find the following resources for your reference:
>
> - RFC: https://wiki.php.net/rfc/marking_return_value_as_important
> - Implementation: https://github.com/php/php-src/pull/17599
>
> Best regards
> Tim Düsterhus
>

I don't see this as something useful when you want to force interactions
with variables. I do see value in using this for the keeping and closing of
resources, but the only error you should ever get is when you use
#[NoDiscard] without a return value.

https://3v4l.org/L4bOc

<?php

#[NoDiscard]
function lockFile(string $path) {
    $handle = fopen($path, 'r+');
    if (! $handle || ! flock($handle, LOCK_EX)) {
        throw new RuntimeException('Failed locking ' . $path);
    }
    return $handle;
}

// what we write
function main() {
    lockFile($path);
    doSomething();
    echo 'hi';
}

// gets rewritten internally to something like
function main() {
    $hidden = lockFile($path);
    doSomething();
    echo 'hi';
    unset($hidden);
}

// if we do assign it, we omit it all
// what we write here would not get rewritten
function main() {
    $handle = lockFile($path);
    doSomething();
    echo 'hi';
}

// if we were to ever get a "using"-like
// what we write
function main() {
    using {
        lockFile($path);
        doSomething();
    }
    echo 'hi';
}

// gets rewritten internally to something like
function main() {
    $hidden = lockFile($path);
    doSomething();
    unset($hidden);
    echo 'hi';
}


Thread (48 messages)

« previous php.internals (#126388) next »