dir

dir(string $directory, ?resource $context = null): Directory|false

The directory object (Directory class: dir() → read() loop → close()) — OOP directory traversal forming three read paradigms with readdir (procedural) and scandir (one-shot materialization); read returns unsorted entries including . and ..

C C23

C23
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

static int cmp(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int main(void) {
    /* fixture dir (POSIX mkdir needs sys/stat.h explicitly) */
    const char *dirpath = "dir_demo_c";
    mkdir(dirpath, 0755);
    const char *files[] = {"b.txt", "a.txt"};
    char path[256];
    for (int i = 0; i < 2; i++) {
        snprintf(path, sizeof(path), "%s/%s", dirpath, files[i]);
        FILE *f = fopen(path, "w");
        fputs("x", f);
        fclose(f);
    }
    snprintf(path, sizeof(path), "%s/sub", dirpath);
    mkdir(path, 0755);
    /* opendir -> readdir loop -> closedir: the API PHP's dir() wraps */
    DIR *d = opendir(dirpath);
    const char *names[64];
    size_t n = 0;
    struct dirent *entry;
    while ((entry = readdir(d)) != NULL) {
        names[n++] = strdup(entry->d_name); /* d_name points to reused storage */
    }
    closedir(d);
    /* deterministic output: collect, sort, then print (includes . and ..) */
    qsort(names, n, sizeof(names[0]), cmp);
    for (size_t i = 0; i < n; i++) {
        printf("%s%s", names[i], i + 1 < n ? "," : "\n");
    }
    return 0;
}
Output
.,..,a.txt,b.txt,sub

C++ C++26

C++26
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main() {
    // std::filesystem::directory_iterator: lazy iteration (no . or ..)
    const std::string base = "dir_demo_cpp";
    std::filesystem::create_directory(base);
    std::ofstream(base + "/b.txt").close();
    std::ofstream(base + "/a.txt").close();
    std::filesystem::create_directory(base + "/sub");
    std::vector<std::string> names;
    for (const auto &e : std::filesystem::directory_iterator(base))
        names.push_back(e.path().filename().string());
    std::sort(names.begin(), names.end());
    std::cout << "directory_iterator (no . or ..)\n";
    for (size_t i = 0; i < names.size(); i++)
        std::cout << names[i] << (i + 1 < names.size() ? "," : "\n");
    return 0;
}
Output
directory_iterator (no . or ..)
a.txt,b.txt,sub

C# v11.0.100

v11.0.100
// Directory.EnumerateFileSystemEntries: lazy enumerable
var baseDir = "dir_demo_cs";
Directory.CreateDirectory(baseDir);
File.WriteAllText(Path.Combine(baseDir, "b.txt"), "x");
File.WriteAllText(Path.Combine(baseDir, "a.txt"), "x");
Directory.CreateDirectory(Path.Combine(baseDir, "sub"));
var names = new List<string>(Directory.EnumerateFileSystemEntries(baseDir));
names.Sort();
Console.WriteLine("EnumerateFileSystemEntries (no . or ..)");
Console.WriteLine(string.Join(",", names.Select(Path.GetFileName)));
Output
EnumerateFileSystemEntries (no . or ..)
a.txt,b.txt,sub

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	// os.ReadDir materializes sorted entries (no . or ..)
	dir := "dir_demo_go"
	os.Mkdir(dir, 0755)
	os.WriteFile(dir+"/b.txt", []byte("x"), 0644)
	os.WriteFile(dir+"/a.txt", []byte("x"), 0644)
	os.Mkdir(dir+"/sub", 0755)
	entries, err := os.ReadDir(dir)
	if err != nil {
		panic(err)
	}
	names := make([]string, 0, len(entries))
	for _, e := range entries {
		names = append(names, e.Name())
	}
	fmt.Println("os.ReadDir (already sorted)")
	fmt.Println(strings.Join(names, ","))
}
Output
os.ReadDir (already sorted)
a.txt,b.txt,sub

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        // Files.newDirectoryStream: lazy iterator (try-with-resources closes it)
        Path base = Path.of("dir_demo_java");
        Files.createDirectory(base);
        Files.writeString(base.resolve("b.txt"), "x");
        Files.writeString(base.resolve("a.txt"), "x");
        Files.createDirectory(base.resolve("sub"));
        List<String> names = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(base)) {
            for (Path p : stream) {
                names.add(p.getFileName().toString());
            }
        }
        names.sort(String::compareTo);
        System.out.println("Files.newDirectoryStream (no . or ..)");
        System.out.println(String.join(",", names));
    }
}
Output
Files.newDirectoryStream (no . or ..)
a.txt,b.txt,sub

JavaScript v26.13.1

v26.13.1
// fs.opendirSync: an OOP handle like PHP's Directory, readSync pulls one entry
const fs = require("node:fs");
fs.mkdirSync("dir_demo_js");
fs.writeFileSync("dir_demo_js/b.txt", "x");
fs.writeFileSync("dir_demo_js/a.txt", "x");
fs.mkdirSync("dir_demo_js/sub");
const d = fs.opendirSync("dir_demo_js");
const names = [];
for (let e = d.readSync(); e !== null; e = d.readSync()) {
  names.push(e.name);
}
d.closeSync();
names.sort();
console.log("fs.opendirSync (no . or ..)");
console.log(names.join(","));
Output
fs.opendirSync (no . or ..)
a.txt,b.txt,sub

PHP v8.6.0

v8.6.0
// Directory object: dir() -> read() loop -> close()
mkdir("dir_demo");
file_put_contents("dir_demo/b.txt", "x");
file_put_contents("dir_demo/a.txt", "x");
mkdir("dir_demo/sub");
$d = dir("dir_demo");
echo get_class($d), "\n";
$names = [];
while (false !== ($e = $d->read())) {
    $names[] = $e;
}
$d->close();
sort($names);
echo implode(",", $names), "\n"; // includes . and .. like readdir()
Output
Directory
.,..,a.txt,b.txt,sub

Python v3.15.2

v3.15.2
# pathlib.Path.iterdir(): lazy iterator of entries (no . or ..)
from pathlib import Path

base = Path("dir_demo_py")
base.mkdir()
(base / "b.txt").write_text("x")
(base / "a.txt").write_text("x")
(base / "sub").mkdir()
it = base.iterdir()  # lazy: one entry per pull
names = sorted(p.name for p in it)
print("Path.iterdir (no . or ..)")
print(",".join(names))
Output
Path.iterdir (no . or ..)
a.txt,b.txt,sub

Rust v1.99.1

v1.99.1
use std::fs;

fn main() {
    // fs::read_dir: lazy iterator of entries (no . or ..)
    let base = "dir_demo_rs";
    fs::create_dir(base).unwrap();
    fs::write(format!("{base}/b.txt"), "x").unwrap();
    fs::write(format!("{base}/a.txt"), "x").unwrap();
    fs::create_dir(format!("{base}/sub")).unwrap();
    let mut names: Vec<String> = fs::read_dir(base)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    println!("fs::read_dir (no . or ..)");
    println!("{}", names.join(","));
}
Output
fs::read_dir (no . or ..)
a.txt,b.txt,sub

TypeScript v26.13.1

v26.13.1
// fs.opendirSync: an OOP handle like PHP's Directory, readSync pulls one entry
import fs from "node:fs";
fs.mkdirSync("dir_demo_ts");
fs.writeFileSync("dir_demo_ts/b.txt", "x");
fs.writeFileSync("dir_demo_ts/a.txt", "x");
fs.mkdirSync("dir_demo_ts/sub");
const d = fs.opendirSync("dir_demo_ts");
const names: string[] = [];
for (let e = d.readSync(); e !== null; e = d.readSync()) {
  names.push(e.name);
}
d.closeSync();
names.sort();
console.log("fs.opendirSync (no . or ..)");
console.log(names.join(","));
Output
fs.opendirSync (no . or ..)
a.txt,b.txt,sub

Language differences

C: opendir/readdir/closedir is exactly what PHP's dir() wraps underneath (example); readdir returns unsorted entries including . and .., and d_name points to reused storage so strdup it — the source of the handle-style read.

C++: std::filesystem::directory_iterator (C++17, example); lazy iteration with no . or .., and incrementing is the object form of readdir.

C#: Directory.EnumerateFileSystemEntries is the lazy enumerable (example); GetFileSystemInfos is in the same family; the Get*Entries forms (without Enumerate) materialize in one shot — the scandir paradigm.

Go: os.ReadDir materializes and sorts (example); for handle-style reads use os.Open plus Readdirnames — the Go team deliberately made the common path deterministic in order.

Java: Files.newDirectoryStream is lazy and closed by try-with-resources (example); Files.list is the same family (Stream form); DirectoryIteratorException wraps runtime IO errors.

JavaScript: fs.opendirSync/readSync/closeSync is structurally identical to PHP's dir() (example); the callback fs.opendir and promise versions coexist; no . or ...

PHP: dir() returns a Directory object with the trio read()/close()/rewind() — rewind resets the handle for re-traversal; read returns unsorted entries (filesystem order) including . and ..; three paradigms compared: dir/readdir procedural-handle style, scandir one-shot materialization, and SPL's DirectoryIterator for full OOP; directory resources are objectified as of PHP 8.5, and dir() is the lightweight entry.

Python: Path.iterdir is a lazy iterator (example); no . or .. and sorting is manual; os.scandir is the materialized version (carrying DirentInfo that caches stat); the legacy os.listdir returns a list in one shot — all three paradigms present here too.

Rust: fs::read_dir is a lazy iterator (example); entries are Result-wrapped (IO errors made explicit), no . or .., and file_name is an OsString needing conversion.

TypeScript: the same opendirSync handle style as Node (example); entries carry isFile/isDirectory discriminators.