Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

WeakReference

Observe an object without prolonging its lifetime. get returns the same live object while a strong reference exists, then null after destruction.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

WeakReference::create($object)

Observe an object without prolonging its lifetime. get returns the same live object while a strong reference exists, then null after destruction. Holding the result of get in another variable temporarily creates a strong reference of its own.

 $obj=new stdClass(); $weak=WeakReference::create($obj); $held=$weak->get(); unset($obj);
$alive=$weak->get()===$held; unset($held); echo json_encode([$alive,$weak->get()]);
[true,null]

Examples

<?php
$obj=new stdClass(); $weak=WeakReference::create($obj); $held=$weak->get(); unset($obj);
$alive=$weak->get()===$held; unset($held); echo json_encode([$alive,$weak->get()]);

Result

[true,null]

Sources