This is an old revision of the document!
Request for Comments: Weak References
- Version: 1.0
- Date: 2011-07-15
- Author: Etienne Kneuss colder@php.net
- Status: Under Discussion
Introduction
This RFC discuss the introduction of weak references in PHP.
Weak Reference
A weak reference is a reference to an object that does not prevent its collection from the garbage collector (GC). Weak references are trying to solve the problem of caches and secondary references in complex data-structures. In such scenarios, the cache prevents the garbage collector from collecting an object, even though it's explicit usage has stopped.
Use Cases
Weak references are useful to allow associating data to existing objects, without having to manually clean this information before the actual object gets collected.
<?php class MyPlop { private $_store = array(); public function getByID($id) { if (isset($this->_store[$id]) && $this->_store[$id]->valid()) { return $this->_store[$id]->get(); } else { // compute $obj $this->_store[$id] = new SplWeakRef($obj); return $obj; } } } $plop = new MyPlop(); $a = $plop->getByID(42); unset($a); // destroys object
Proposal and Patch
Proposal is a SplWeakRef class, which implements some magic to allow GC collection. SplWeakRef would have the following prototype:
void SplWeakRef::__construct(object ref) object SplWeakRef::get() bool SplWeakRef::valid()
Patch is available here: http://patches.colder.ch/php-src/weakref-trunk.patch?markup