EricAto
EricAto

Reputation: 1

Initialize objects of another class in PHP

I have 4 files index.php, Database.php, Zoo.php, Animal.php

// Zoo.php

class Zoo {
    private $db;
    private $animals = array();

    public function __constructor(Database $db) {
        $this->db = $db;
        $this->getAllAnimals();
    }

    private function getAllAnimals() {
        //Database stuff, returns an array with all animals
        $p=0;
        foreach($dbresult as $an){
            $animals[$p++] = new Animal($an['name'], $an['age'], $an['weight']);
        }
    }

    public function listAnimals() {
        foreach ($this->animals as $a){
            echo $a->name;
            //and so on
        }
    }
}

// Animal.php

class Animal {
    // variables for the animals
}

// index.php

<?php
    include 'Database.php';
    include 'Zoo.php';

    $db = new Database();
    $zoo = new Zoo($db);
    $zoo->listAnimals();
?>  

This is from the top of my head, so if there are some errors, just treat it as pseudocode :)

My problem:
I get a Fatal Error Class Animal not found. If I add include 'Animal.php'; in the first line of Zoo.php, right before class Zoo { it works.

I'm stil learning about OOP with php, and the include-line strikes me as odd, so I ask for someone to help me out with this.
Is there another way to use "Animal"-objects in the "Zoo"-class, without the include or is it normal to use include, or maybe require/require_once?

Upvotes: 0

Views: 1215

Answers (3)

Mark Baker
Mark Baker

Reputation: 212522

I believe that most OOP developers these days take advantage of __autoload or (even better) the SPL autoloader, even if only in the libraries and frameworks that they use.

Upvotes: 1

jgroenen
jgroenen

Reputation: 1326

If you need the "Animal" class inside Zoo.php, require_once("Animal.php"); at the top of Zoo.php. If you need it in some other file, do the same over there.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

the include-line strikes me as odd

Why's that, then? To use Animal you must include its definition. Always seemed pretty rational to me.

There are alternatives such as require and require_once that do the same thing (but with some added restrictions), and some more exotic alternatives such as autoloading. But for simple tasks, include will do just fine.

Upvotes: 0

Related Questions