Circular references in PHP are a common cause of memory leaks. Circular references occur when objects refer to each other, directly or indirectly. Fortunately, PHP has a garbage collector that can detect and clean up circular references. However, this consumes CPU cycles and may slow down the application.
The garbage collector is triggered when there are 10,000 possible loop objects or arrays in memory and one of them goes out of scope.
If you have a small number of objects that use a lot of memory, garbage collection will never be triggered. You may hit the memory limit even if the memory is used by orphaned objects that the garbage collector is supposed to collect.
This is why you should identify situations that create circular references and avoid them.
Ideally, for web applications, you want to disable the garbage collector and let PHP release all memory after sending the response. But this is dangerous for long-running scripts such as daemons or worker processes, as memory leaks can accumulate over time and slow down the application through frequent calls to the garbage collector.
In this article, we will explore how closures and generators save circular references and how to prevent them.
- About circular references
- Typical example of circular reference
- Use weak references to prevent circular references
- Closures and circular references
- Generators and circular references
- Conclusion
About circular references
Typical example of circular reference
class A { public B $b; public function __construct() { $this->b = new B($this); } } class B { public function __construct(public A $a) {} }
In this example, A and B refer to each other. When you create an instance of A, it creates an instance of B that references A. This creates a circular reference.
To detect circular references, we can manually trigger the garbage collector using gc_collect_cycles()
and read the number of collected references using gc_status()
.
// 創(chuàng)建的對(duì)象但未分配給變量 new A(); gc_collect_cycles(); print_r(gc_status());
This will output:
<code>Array ( ... [collected] => 2 ... )</code>
This example shows that the garbage collector has detected and deleted 2 objects with circular references.
You can also use the xdebug_debug_zval()
function to view the number of references to an object.
Use weak references to prevent circular references
When encountering circular references, a simple solution is to use weak references. A weak reference is an object that holds a reference that does not prevent the garbage collector from collecting the object it refers to. In PHP you can create weak references using the WeakReference
class.
This requires some changes to the code. Class B now stores WeakReference
objects instead of A objects. You must access the A object using the WeakReference
object's get()
method.
class A { public B $b; public function __construct() { $this->b = new B($this); } } class B { /** @var WeakReference<a> $a */ public WeakReference $a; public function __construct(A $a) { $this->a = WeakReference::create($a); } }
// 創(chuàng)建的對(duì)象但未分配給變量 new A(); gc_collect_cycles(); print_r(gc_status()); // [collected] => 0
In the output you will see that the number of citations collected is now 0.
Tip 1: Use weak references only when necessary to prevent circular references.
Closures and circular references
The concept of closure in PHP is to create a function that can access variables in the parent scope. This can lead to circular references if you're not careful.
class A { public B $b; public function __construct() { $this->b = new B($this); } } class B { public function __construct(public A $a) {} }
In this example, the closure $a->b
refers to a variable $a
in the parent scope. Circular references are easy to spot because the references are unambiguous.
However, the same problem can arise in a more subtle way if you use the shorthand syntax of closures. With arrow functions, the variable $a
is not explicitly referenced in the closure, but it is still captured by reference.
// 創(chuàng)建的對(duì)象但未分配給變量 new A(); gc_collect_cycles(); print_r(gc_status());
In this example, the number of references collected is 2, indicating a circular reference.
Reference to $this in closure
Any non-static closure created within a class method will have a reference to the object instance ($this
) even if $this
is not accessed.
<code>Array ( ... [collected] => 2 ... )</code>
This is because $this
references are always captured by reference in closures. It can be accessed using Reflection::getClosureThis()
.
class A { public B $b; public function __construct() { $this->b = new B($this); } } class B { /** @var WeakReference<a> $a */ public WeakReference $a; public function __construct(A $a) { $this->a = WeakReference::create($a); } }
If the closure is created from the global scope or a static method, the $this
reference is null.
Tip 2: If you don’t need
$this
, always usestatic function () {}
orstatic fn () =>
to create a closure.
Generators and circular references
Let’s talk about the reason for this article. I recently discovered something: Generators retain references as long as they are not exhausted.
In this example, the class stores the generator in a property, but the generator has a $this
reference to the object instance.
A generator behaves like a closure and holds a reference to the object instance.
// 創(chuàng)建的對(duì)象但未分配給變量 new A(); gc_collect_cycles(); print_r(gc_status()); // [collected] => 0
The class instance is collected by the garbage collector because it has a reference to the generator, which has a reference to the object instance.
Once the generator is exhausted, the reference is released and the object instance is removed from memory.
function createCircularReference() { $a = new stdClass(); $a->b = function () use ($a) { return $a; }; return $a; }
Tip 3: Always exhaust the generator through iteration.
Tip 4: Use static methods or closures to create generators to avoid retaining references to object instances.
Conclusion
Circular references are a common cause of memory leaks in PHP. Even if the garbage collector can detect and clean up circular references, it consumes CPU cycles and may slow down the application. You must detect situations that create such circular references and adjust your code to prevent them. Using weak references can prevent reference cycles, but some simple tips can help you prevent them in the first place:
- If
$this
is not required, usestatic function () {}
orstatic fn () =>
to create a closure. - Always exhaust the generator through iteration.
- Use static methods or closures to create generators to avoid retaining references to object instances.
Read more
- PHP Garbage Collection - Performance Considerations
- What is garbage collection in PHP? How to make the most of it?
- memprof - Memory analyzer for PHP. Help find memory leaks in PHP scripts.
- Xdebug’s built-in analyzer
The above is the detailed content of PHP Closures and Generators can hold circular references. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
