The WeakRef class

(PECL weakref >= 0.1.0)

Introduction

The WeakRef class provides a gateway to objects without preventing the garbage collector from freeing those objects. It also provides a way to turn a weak reference into a strong one.

Class synopsis

WeakRef {
/* Methods */
public Weakref::__construct ([ object $object ] )
public bool Weakref::acquire ( void )
public object Weakref::get ( void )
public bool Weakref::release ( void )
public bool Weakref::valid ( void )
}

Examples

Example #1 WeakRef usage example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new WeakRef($o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}

unset(
$o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

Table of Contents