Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP WeakReference class
PHP's WeakReference class allows you to retain a reference to an object without preventing the garbage collector from destroying it. This is useful for implementing cache-like structures without memory issues, as the object can be freed when no strong references remain.
What are Weak References?
A weak reference differs from a normal reference because it doesn't prevent garbage collection. When all strong references to an object are removed, the object is immediately destroyed, even if weak references still exist. This enables efficient caching without memory leaks.
Syntax
WeakReference {
/* Methods */
public __construct ( void )
public static create ( object $referent ) : WeakReference
public get ( void ) : ?object
}
Methods
WeakReference::__construct() − Disallows direct instantiation. Use the factory method WeakReference::create() instead.
WeakReference::create(object $referent) − Creates a new weak reference to the given object.
WeakReference::get() − Returns the weakly referenced object, or NULL if it has been garbage collected.
Note: WeakReference was introduced in PHP 7.4. For earlier versions, the
weakrefextension provided similar functionality.
Example
This example demonstrates how weak references behave when the original object is destroyed ?
<?php
class MyClass {
public function hello() {
echo "Hello World!";
}
}
// Create an object and weak reference
$obj = new MyClass();
$weakRef = WeakReference::create($obj);
// Check if object exists via weak reference
echo "Before unset:<br>";
var_dump($weakRef->get());
// Remove the strong reference
unset($obj);
// Check weak reference again
echo "\nAfter unset:<br>";
var_dump($weakRef->get());
?>
Before unset:
object(MyClass)#1 (0) {
}
After unset:
NULL
Use Cases
WeakReference is particularly useful for:
- Cache implementations that don't hold objects in memory indefinitely
- Observer patterns where observers shouldn't prevent subject destruction
- Parent-child relationships avoiding circular references
Conclusion
WeakReference provides memory-efficient object referencing by allowing garbage collection when strong references are removed. It's essential for building caches and avoiding memory leaks in complex object relationships.
