Table of Contents

PHP RFC: Change Directory class to behave like a resource object

Introduction

The Directory class is probably the first instance of what we now call a “resource object” (and in its stricter sense an “opaque object”). Resource/Opaque objects are usually the result of converting resources to objects, which in general implies, being final, not serializable, not constructible via new, cannot be cast, and does not implement any methods. However, as this class has existed since PHP 4 none of these things are formally implemented.

Valid instances of this class are created by calling the dir() function. But one can create a broken instance by just using new Directory(), which is visible if one tries to call one of its methods.

As it seems likely that we will repurpose this class when converting directory resources to objects, we think it makes sense to already convert this class to behave like a resource object.

Proposal

We propose to make the following changes to the Directory class:

Rationales

Preventing initialization via new

The stream layer of PHP emits warnings and may result in uninitialized streams. Constructors must always either throw an exception, or create a valid object. As these semantics are not straightforward to implement when creating streams we continue to rely on dir() to create instances of this class as it does not have the above constraints.

Making the class final

As this class is a wrapper around an internal stream resource, and cannot be properly initialized without it being returned by dir(), extending it doesn't make any sense.

Preventing cloning

As this class is a wrapper around an internal stream resource, and there is no capability to duplicate streams, there is no reasonable way to implement cloning.

Preventing serialization

Trying to serialize (and unserialize) the state of a given file system doesn't make any sense.

Preventing the creation of dynamic properties

Creating a dynamic property on an instance of this class points to a definite bug.

Backward Incompatible Changes

It will no longer be possible:

Version

Next minor version, i.e. PHP 8.5.

Vote

As per the voting RFC a yes/no vote with a 2/3 majority is needed for this proposal to be accepted.

Voting started on 2024-10-03 and will end on 2024-10-20.

Accept Change Directory class to behave like a resource object RFC?
Real name Yes No
ashnazg (ashnazg)  
ayesh (ayesh)  
bwoebi (bwoebi)  
cmb (cmb)  
cpriest (cpriest)  
cschneid (cschneid)  
devnexen (devnexen)  
galvao (galvao)  
girgias (girgias)  
ilutov (ilutov)  
imsop (imsop)  
jimw (jimw)  
klaussilveira (klaussilveira)  
mauricio (mauricio)  
mbeccati (mbeccati)  
mcmic (mcmic)  
nielsdos (nielsdos)  
petk (petk)  
rasmus (rasmus)  
santiagolizardo (santiagolizardo)  
sergey (sergey)  
theodorejb (theodorejb)  
timwolla (timwolla)  
Final result: 23 0
This poll has been closed.

Future scope

References