Manual class loading with require

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

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

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

Here we have three files. One file (“Animal.php”) defines the class. This file has no side effects besides defining the class and neatly keeps all the knowledge about an “Animal” in one place. It’s easily version controlled. It’s easily reused.

Two files consume the “Animal.php” file by manually require-ing the file. Again, PHP reads source files top-to-bottom, so the require goes and finds the “Animal.php” file and makes the Animal class definition available before calling new Animal.

Now imagine we had dozens or hundreds of cases where we wanted to perform new Animal. That would require (pun-intended) many, many require statements that are very tedious to code.

Feedback about page:

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



Table Of Contents