Table of Contents

PHP RFC: Weak References

Introduction

Weak References allow the programmer to retain a reference to an object which does not prevent the object from being destroyed; They are useful for implementing cache like structures. They are currently supported in PHP by extension.

The current implementations of WeakRef all work by overloading object handlers, the most popular implementation (pecl-weakref) changes stack allocated read only memory and will be rendered unusable by PHP 7.3. Other implementations that change object handlers in some other way also risk faulting and rely on undefined behaviour and casting away constness.

Other implementations are possible, krakjoe/uref is an implementation that uses low level features (mprotect, 0xCC, signals) to implement weakrefs, but at the cost of portability, generating segfaults, protecting memory, and implicit signal handler restrictions.

In principle weak referencing an object is not complicated, and only requires the (ab)use of Zend or layers beneath because we do not directly support it.

Proposal

We directly support weak referencing in the simplest possible way.

API

The proposed API:

final class WeakReference {
    public static function create(object $object) : WeakReference;
 
    public function get() : ?object;
}

The proposed API differs from the documented WeakRef class. The currently documented API includes the following methods omitted from the proposed API:

Acquire and release are sugar for get and unset, and valid is simply superfluous since the get method will not throw an exception and null is a falsy value.

Implementation Details

The proposed API:

Backward Incompatible Changes

None

Proposed PHP Version(s)

PHP 7.4

RFC Impact

To SAPIs

None

To Existing Extensions

None

To Opcache

None

New Constants

None

php.ini Defaults

None

Open Issues

None

Unaffected PHP Functionality

All

Proposed Voting Choices

Simple Yes/No, requires super majority.

Implement weakrefs ?
Real name Yes No
ajf (ajf)  
ashnazg (ashnazg)  
bishop (bishop)  
bwoebi (bwoebi)  
carusogabriel (carusogabriel)  
cmb (cmb)  
cpriest (cpriest)  
derick (derick)  
diegopires (diegopires)  
duncan3dc (duncan3dc)  
emir (emir)  
galvao (galvao)  
gasolwu (gasolwu)  
hywan (hywan)  
jhdxr (jhdxr)  
kalle (kalle)  
kguest (kguest)  
krakjoe (krakjoe)  
laruence (laruence)  
lex (lex)  
lstrojny (lstrojny)  
malukenho (malukenho)  
mike (mike)  
nikic (nikic)  
ocramius (ocramius)  
pauloelr (pauloelr)  
petk (petk)  
pollita (pollita)  
ramsey (ramsey)  
rasmus (rasmus)  
rtheunissen (rtheunissen)  
sebastian (sebastian)  
trowski (trowski)  
Final result: 28 5
This poll has been closed.

Voting started 2019-02-22, ends 2019-03-08.

Patches and Tests

https://github.com/php/php-src/pull/3787

References

Announce: https://externals.io/message/102111

Re-announce: https://externals.io/message/104014