PHP Manual class loading with require

Download PHP for free


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

// zoo.php
require 'Animal.php';
$animal = new Animal;

// aquarium.php
require 'Animal.php';
$animal = new Animal;

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.

BC Math (Binary Calculator)