Autoloading replaces manual class definition loading

suggest change
// autoload.php
spl_autoload_register(function ($class) {
    require_once "$class.php";
});

// Animal.php
class Animal {
    public function eats($food) {
         echo "Yum, $food!";
    }
}

// zoo.php
require 'autoload.php';
$animal = new Animal;
$animal->eats('slop');

// aquarium.php
require 'autoload.php';
$animal = new Animal;
$animal->eats('shrimp');

Compare this to the other examples. Notice how require "Animal.php" was replaced with require "autoload.php". We’re still including an external file at run-time, but rather than including a specific class definition we’re including logic that can include any class. It’s a level of indirection that eases our development. Instead of writing one require for every class we need, we write one require for all classes. We can replace N require with 1 require.

The magic happens with spl_autoload_register. This PHP function takes a closure and adds the closure to a queue of closures. When PHP encounters a class for which it has no definition, PHP hands the class name to each closure in the queue. If the class exists after calling a closure, PHP returns to its previous business. If the class fails to exist after trying the entire queue, PHP crashes with “Class ‘Whatever’ not found.”

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Autoloading primer:
* Autoloading replaces manual class definition loading

Table Of Contents
2 Arrays
4 Types
5 Autoloading primer
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR