Home > Backend Development > PHP Tutorial > PHP Closures and Generators can hold circular references

PHP Closures and Generators can hold circular references

Patricia Arquette
Release: 2025-01-18 06:03:09
Original
426 people have browsed it

PHP Closures and Generators can hold circular references

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) {}
}
Copy after login
Copy after login

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().

// 创建的对象但未分配给变量
new A();

gc_collect_cycles();
print_r(gc_status());
Copy after login
Copy after login

This will output:

<code>Array
(
    ...
    [collected] => 2
    ...
)</code>
Copy after login
Copy after login

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);    
    }
}
Copy after login
Copy after login
// 创建的对象但未分配给变量
new A();

gc_collect_cycles();
print_r(gc_status());
// [collected] => 0
Copy after login
Copy after login

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) {}
}
Copy after login
Copy after login

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.

// 创建的对象但未分配给变量
new A();

gc_collect_cycles();
print_r(gc_status());
Copy after login
Copy after login

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>
Copy after login
Copy after login

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);    
    }
}
Copy after login
Copy after login

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 use static function () {} or static 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.

// 创建的对象但未分配给变量
new A();

gc_collect_cycles();
print_r(gc_status());
// [collected] => 0
Copy after login
Copy after login

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;
}
Copy after login

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, use static function () {} or static 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template