0plus1
0plus1

Reputation: 4555

How do I create a class that contains several classes that can communicate with each other?

I'm trying to take full advantage of object oriented php and learn something along the way. Following an MVC tutorial I was able to do this:

class Repository {

    private $vars = array();

    public function __set($index, $value){
        $this->vars[$index] = $value;
    }

    public function __get($index){
        return $this->vars[$index];
    }
}
/*
*/
function __autoload($class_name) {
    $filename = strtolower($class_name) . '.class.php';
    $path = dirname(__FILE__);
    $file = $path.'/classes/' . $filename;

    if (file_exists($file) == false){
        return false;
    }
    include ($file);
}
//Main class intialization
$repo = new Repository;
//Configuration loading
$repo->config = $config;
//Classes loading
$repo->common = new Common($repo);
$repo->db = new Database($repo);
$repo->main = new Main($repo);

Then each class would follow this template:

class Database{

    private $repo;

    function __construct($repo) {
        $this->repo= $repo;
    }
}

This way I can access all the methods and vars of the classes that are loaded before the one I'm in. In the example before I can do this in the main class:

$this->repo->db->someMethod();

The thing that strikes me is that the object $repo gets duplicated each time that a new class is loaded is this a problem memory wise? Are there better ways to do this? Is this something that can be used in a real project?

Thank you very much

Upvotes: 1

Views: 550

Answers (1)

Nicolas78
Nicolas78

Reputation: 5144

I'm not quite sure what you're trying to achieve (I guess there's some metacomment coming about how to do this differently ;), but you can relax about memory consumption; you're only passing on references to the same object, so all that's duplicated is 4 bytes worth of pointer to the object instance!

Nic

Upvotes: 3

Related Questions