[PHP-NOTES] note 130422 added to function.gc-collect-cycles

[email protected] ("[email protected]") Mon, 21 Jul 2025 09:05:43 +0000 (UTC)
Newsgroups php.notes
Message-ID <[email protected]>
<?php gc_collect_cycles(); ?> triggers PHP's garbage collector to explicitly search for and clean up circular references - objects that reference each other but are no longer accessible by the program.

Although PHP's garbage collector runs automatically, in long-running scripts or memory-intensive operations (such as daemons, CLI tools, or large loops), calling this function manually can help reduce memory usage and prevent memory leaks.

Example:

<?php

class Node {
    public $ref;
}

$a = new Node();
$b = new Node();

$a->ref = $b;
$b->ref = $a;

unset($a, $b);

// At this point, $a and $b are no longer accessible, but the circular reference remains in memory.
// Force cleanup:
$collected = gc_collect_cycles();

echo "Collected cycles: $collected\n";
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 109.72.53.236)
----
Manual Page -- https://php.net/manual/en/function.gc-collect-cycles.php
Edit        -- https://main.php.net/note/edit/130422
Del: integrated  -- https://main.php.net/note/delete/130422/integrated
Del: useless     -- https://main.php.net/note/delete/130422/useless
Del: bad code    -- https://main.php.net/note/delete/130422/bad+code
Del: spam        -- https://main.php.net/note/delete/130422/spam
Del: non-english -- https://main.php.net/note/delete/130422/non-english
Del: in docs     -- https://main.php.net/note/delete/130422/in+docs
Del: other reasons-- https://main.php.net/note/delete/130422
Reject      -- https://main.php.net/note/reject/130422
Search      -- https://main.php.net/manage/user-notes.php