Hi Rowan,

Rowan wrote:
> For that to work, it would require the variable to be captured by
> reference, not value.
> ...
> The only way for it to work would be using capture by reference (not
> supported by the proposed short syntax):

I wrote about this before. Some of the words in the RFC are, in my
opinion, quite inaccurate:

Danack wrote in https://news-web.php.net/php.internals/117938 :
> Those statements are true for scalar values. They are not true for objects:

With automatic capturing of variables, for the code example I gave the
user would want the variable to be captured, and to them it looks like
it should be, but because of an optimization it is not.

When the code doesn't work as they expect it to, the programmer is
likely to add a var_dump to try to see what is happening. Which makes
it look like their code 'should' work, as their resource object is
still alive.

> In fact, the "optimisation" is in my opinion a critical part of the
> semantics, to avoid the opposite problem:

As I said, I think that problem is a lot easier to explain "either use
long closures or change your variable name if you don't want it
captured." than trying to explain "yes, the variable is referenced
inside the closure, but it's not captured because you aren't reading
from it".

cheers
Dan
Ack


For this code, comment the var_dump in/out to affect the lifetime of the object.

class ResourceType
{
    public function __destruct() {
        echo "Resource is released.\n";
    }
}

function get_callback()
{
    $some_resource = new ResourceType();
    $fn = fn() {
        // // why is my lock released?
        var_dump($some_resource);
        // "Free that resource"
        $some_resource = null;
    };
    return $fn;
}

$fn = get_callback();
echo "Before callback\n";
$fn();
echo "After callback\n";

// Without var_dump
Resource is released.
Before callback
After callback

// With var_dump
Before callback
object(ResourceType)#1 (0) {
}
After callback
Resource is released.

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to