PHP.nl

spl_autoload_register

spl_autoload_register

Register given function as __autoload() implementation

bool **spl_autoload_register**  $callback bool $throw bool $prepend

Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.

If your code has an existing function then this function must be explicitly registered on the __autoload queue. This is because will effectively replace the engine cache for the function by either or . __autoload``spl_autoload_register``__autoload``spl_autoload``spl_autoload_call

If there must be multiple autoload functions,
allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, may only be defined once. spl_autoload_register``__autoload

callback The autoload function being registered. If null, then the default implementation of will be registered.
spl_autoload

void **** string $class
   The  will not contain the leading
   backslash of a fully-qualified identifier.
  `class`

throw This parameter specifies whether should throw exceptions when the cannot be registered. spl_autoload_register``callback

Waarschuwing: > This parameter is ignored as of PHP 8.0.0, and a notice will be emitted if set to false. will now always throw a on invalid arguments. spl_autoload_register``TypeError

prepend If true, will prepend the autoloader on the autoload queue instead of appending it. spl_autoload_register

return.success

Voorbeeld: as a replacement for an function

<?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

?>

Voorbeeld: example where the class is not loaded

<?php

namespace Foobar;

class Foo {
    static public function test($class) {
        print '[['. $class .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test');

new InexistentClass;

?>
[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

Voorbeeld: The identifier will be provided without the leading backslash

<?php

spl_autoload_register(static function ($class) {
    var_dump($class);
});

class_exists('RelativeName');
class_exists('RelativeName\\WithNamespace');
class_exists('\\AbsoluteName');
class_exists('\\AbsoluteName\\WithNamespace');

?>
string(12) "RelativeName"
string(26) "RelativeName\WithNamespace"
string(12) "AbsoluteName"
string(26) "AbsoluteName\WithNamespace"

__autoload