Weak references are well known pattern in many programing languages which have automatic garbage collection such as: .NET, Java, Python, PHP [2].

Garbage Collection

Most of high level programming languages have garbage collector(s) to reduce programmers’ mental load. Those languages take care of releasing useless objects. This sounds good! Programmers don't have to care about memory any more.

But it doesn't mean you can use memory as your wish without care about memory, even though there is a garbage collector. Basically garbage means different things between languages and programmers.

  • Language's perspective: If an object is not reachable . Then the collector need to release it.
  • Programmer's perspective: If an object is no longer needed. It should be released.

We can tell the difference easily, a programmer's garbage may not a garbage of the language. We call keep a piece of useless object in memory as leaking.

Not reachable means there is no way to access that object any more. But no longer needed means logically that object is useless.

Why do we need weak references?

We need to manage our memory carefully.

We want to reference an object without interfere the lifetime of that object.

Since we are talking about weak references, there must be strong references.

What does a strong reference means? It means that only all of the reference are gone (out of scope or been manually unset) then the object can be freed.

function main() {  
    $a = new stdClass();
    $b = $a;


The assignment create a strong reference between the variable $a and the new created object. So does variable $b it is a strong reference to the object (We won’t talk about Copy-On-Write here).

After function main() complete execution. The new object could be released because both of the reference are gone, then the GC could collect the garbage. Let's take a look at another example:

function main(){  
    $a = new stdClass();
    $b = $a;
    return $b;
$stdObj = main();

after the main function being executed, the object won’t be freed because it was referenced by $stdObj we can’t free it.

PHP itself didn’t have the concept of weak references. But there is an extension called php-weakref which implemented weak references.

In different languages there are different implementations. Java have two more weak references: soft references and phantom references. You can read the blog: [https://weblogs.java.net/blog/2006/05/04/understanding-weak-references].