Skip to content

WeakMap prevents garbage collection #10043

Closed
@nicolas-grekas

Description

@nicolas-grekas

Description

I have a situation where I create an object graph similar to this one:

class Canary extends stdClass
{
    public function __construct(public string $name)
    {
    }

    function __destruct()
    {
        echo $this->name."\n";
    }
}

$container = new Canary('container');
$canary = new Canary('canary');
$container->canary = $canary;

$map = new \WeakMap();
$map[$canary] = $container;

echo 1;
unset($container, $canary);
gc_collect_cycles();
echo 2;

Resulted in this output:

12
container
canary

But I expected this output instead:

1container
canary
2

Commenting the $map[$canary] = $container; line generates the expected output.

A simpler reproducer is this one:

$canary = new Canary('canary');

$map = new \WeakMap();
$map[$canary] = $canary;

echo 1;
unset($canary);
gc_collect_cycles();
echo 2;

Which resulted in this output:

12
canary

But I expected this output instead:

1canary
2

PHP Version

PHP >= 8.0

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions