spl_autoload_register

spl_autoload_register(?callable $callback = null, bool $throw = true, bool $prepend = false): bool

Registers a function into the SPL autoload queue; it fires on demand the first time an undefined class is used.

C C23

C23
#include <stdio.h>
#include <string.h>

/* C has no runtime class loading; the lowest-level truth is manual dynamic
   linking (dlopen/LoadLibrary). A static factory registry shows the shape: */
typedef void (*greet_fn)(void);

static void hello_greet(void) {
    printf("hello from Hello\n");
}

static greet_fn registry_lookup(const char *name) {
    if (strcmp(name, "Hello") == 0) return hello_greet;
    return NULL;
}

int main(void) {
    greet_fn g = registry_lookup("Hello"); /* resolved on demand */
    if (g != NULL) g();
    printf("lookup Unknown: %s\n", registry_lookup("Unknown") == NULL ? "miss" : "hit");
    return 0;
}
Output
hello from Hello
lookup Unknown: miss

C++ C++26

C++26
#include <iostream>
#include <string>
#include <unordered_map>

// C++ links at compile time; runtime class loading is hand-rolled (dlopen on
// POSIX). A name-keyed factory registry shows the on-demand-load shape:
namespace autoload {
    using Greet = void (*)();
    std::unordered_map<std::string, Greet> table = {
        {"Hello", [] { std::cout << "hello from Hello\n"; }},
    };
    Greet load(const std::string& name) {
        auto it = table.find(name);
        return it == table.end() ? nullptr : it->second;
    }
}

int main() {
    if (auto g = autoload::load("Hello")) g();
    std::cout << "lookup Unknown: " << (autoload::load("Unknown") == nullptr ? "miss" : "hit") << "\n";
    return 0;
}
Output
hello from Hello
lookup Unknown: miss

C# v11.0.100

v11.0.100
using System;
using System.Reflection;

// C# triggers assembly-level on-demand loading (JIT/type system resolves on
// first use); Assembly.Load pulls a named assembly in at runtime.
// The base profile always ships System.Runtime, so the load is deterministic.
Assembly asm = Assembly.Load("System.Runtime");
Console.WriteLine(asm.GetName().Name); // stable assembly identity
Console.WriteLine(asm.IsDynamic ? "dynamic" : "static");
// Missing types are probed with Type.GetType + throwOnError:false
Type? miss = Type.GetType("NoSuch.Class.A20", throwOnError: false);
Console.WriteLine(miss == null ? "missing returns null" : "found");
Output
System.Runtime
static
missing returns null

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sync"
)

// Go links all packages at compile time; there is no runtime class autoload.
// The closest idiom is a lazy singleton built on sync.Once:
type greeter struct{ name string }

var (
	once   sync.Once
	shared *greeter
)

func getGreeter() *greeter {
	once.Do(func() {
		fmt.Println("creating on first use")
		shared = &greeter{name: "Hello"}
	})
	return shared
}

func main() {
	_ = getGreeter() // touch triggers construction
	fmt.Println(getGreeter().name)
}
Output
creating on first use
Hello

Java v27.0.1

v27.0.1
// Java: ClassLoader loads .class files on demand on first touch;
// the static initializer proves the moment of loading
class Hello {
    static {
        System.out.println("static init runs on first touch");
    }
}

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> c = Class.forName("Hello"); // triggers loading + static init
        System.out.println(c.getSimpleName());
    }
}
Output
static init runs on first touch
Hello

JavaScript v26.13.1

v26.13.1
// JS: dynamic import() loads modules on demand, but at the language level
// there is no class table — frameworks emulate autoload via lazy registries
const registry = new Map();
function autoload(name, factory) {
  if (!registry.has(name)) registry.set(name, factory()); // lazy on first touch
  return registry.get(name);
}
console.log(registry.size === 0 ? "empty" : "has entries");
const hello = autoload("Hello", () => ({ greet: () => "hello from Hello" }));
console.log(hello.greet());
console.log(registry.size === 1 ? "loaded on demand" : "eager");
const again = autoload("Hello", () => { throw new Error("should not run"); });
console.log(again.greet());
Output
empty
hello from Hello
loaded on demand
hello from Hello

PHP v8.6.0

v8.6.0
// Demo class file in the system temp dir (works in containers/CI alike)
$dir = sys_get_temp_dir() . "/php_autoload_demo_a20";
if (!is_dir($dir)) mkdir($dir);
file_put_contents("$dir/HelloAutoloaded.php", "<?php\nclass HelloAutoloaded {}\n");
// Register an autoloader: fired lazily on the first touch of a missing class
spl_autoload_register(function (string $class) use ($dir): void {
    $file = $dir . "/" . $class . ".php";
    if (is_file($file)) require $file;
});
var_dump(class_exists("HelloAutoloaded", false)); // no autoload trigger
var_dump(class_exists("HelloAutoloaded"));        // autoload fires and succeeds
var_dump(class_exists("NoSuchClassA20"));         // loader finds nothing, still false
Output
bool(false)
bool(true)
bool(false)

Python v3.15.2

v3.15.2
import importlib.abc
import importlib.machinery
import sys
import types

# Python's import machinery is a chain of finders/loaders (sys.meta_path);
# inserting a finder is the hook that mirrors spl_autoload_register
module_name = "hello_autoloaded"
loaded = {}

class LazyLoader(importlib.abc.Loader):
    def create_module(self, spec):
        mod = types.ModuleType(spec.name)
        mod.greeting = "hi"
        loaded[spec.name] = True
        return mod

    def exec_module(self, module):
        pass

class LazyFinder(importlib.abc.MetaPathFinder):
    def find_spec(self, fullname, path=None, target=None):
        if fullname == module_name:
            return importlib.machinery.ModuleSpec(fullname, LazyLoader())
        return None

sys.meta_path.insert(0, LazyFinder())
print(module_name in loaded)   # False - nothing loaded yet
mod = __import__(module_name)  # first touch triggers finder + loader
print(module_name in loaded)   # True - loaded on demand
print(mod.greeting)
Output
False
True
hi

Rust v1.99.1

v1.99.1
// Rust links everything at compile time; there is no runtime class autoload.
// The closest idiom is lazy construction on first use (std::sync::OnceLock):
use std::sync::OnceLock;

struct Greeter {
    name: &'static str,
}

static GREETER: OnceLock<Greeter> = OnceLock::new();

fn get_greeter() -> &'static Greeter {
    GREETER.get_or_init(|| {
        println!("creating on first use");
        Greeter { name: "Hello" }
    })
}

fn main() {
    let _ = get_greeter().name.len(); // touch triggers construction
    println!("{}", get_greeter().name);
}
Output
creating on first use
Hello

TypeScript v26.13.1

v26.13.1
// TS: same runtime registry as JS; types are compile-time only, so the
// runtime has no class table to consult — lazy factories fill that gap
const registry = new Map<string, { greet: () => string }>();
function autoload(name: string, factory: () => { greet: () => string }): { greet: () => string } {
  if (!registry.has(name)) registry.set(name, factory()); // lazy on first touch
  return registry.get(name)!;
}
console.log(registry.size === 0 ? "empty" : "has entries");
const hello = autoload("Hello", () => ({ greet: () => "hello from Hello" }));
console.log(hello.greet());
console.log(registry.size === 1 ? "loaded on demand" : "eager");
Output
empty
hello from Hello
loaded on demand

Language differences

C: no runtime class loading — the lowest-level truth is manual dynamic linking: POSIX dlopen/dlsym (<dlfcn.h>, needs -ldl on some platforms), Windows LoadLibrary; the example first shows the on-demand-resolve shape with a static factory registry.

C++: compile-time linking; runtime loading is likewise hand-rolled dlopen (or emulated with a std::function registry, as written); plugin systems are the main battlefield.

C#: on-demand loading is per-assembly — Assembly.Load pulls it in at runtime and the JIT/type system resolves types on first use; Type.GetType with throwOnError:false is the existence probe (example).

Go: everything links at compile time, no runtime class autoload — the closest idiom is a sync.Once lazy singleton (example); plugins are limited to the plugin package.

Java: the ClassLoader hierarchy is the ancestor of layered auto-loading — first touch triggers loading + static init (example uses Class.forName); Spring component scanning is the application-level equivalent.

JavaScript: dynamic import() fetches modules on demand (returns a Promise); the language has no class table, frameworks emulate autoload with lazy registries/factories (example).

PHP: autoloaders registered with spl_autoload_register queue in registration order and are tried one by one on first touch of a class (new/class_exists/calling an undefined class); composer's PSR-4 ecosystem is one standard mapping rule plus one generic loader registered via spl_autoload_register — the whole ecosystem registers once.

Python: the import system is itself a hook chain — finders/loaders on sys.meta_path fire via __import__ (example); lower-level and more customizable than PHP, but conceptually isomorphic: resolve on first touch.

Rust: compile-time linking, no runtime class loading — the closest idiom is OnceLock lazy construction (example); cfg/feature probing is all compile-time.

TypeScript: runtime identical to JavaScript (lazy registry example); types are erased at compile time, leaving no runtime class table.