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 load Animal.php with require. That statement runs before new Animal, so the class exists when it is instantiated. A class in another file is not available until that file is loaded.

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