1

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

bcosca
  • 17,371
  • 5
  • 40
  • 51
0plus1
  • 4,475
  • 12
  • 47
  • 89
  • 1
    Related and possibly good reading: http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-organize-and-access-your-helper-objects – Pekka Aug 16 '10 at 10:10

1 Answers1

3

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

Nicolas78
  • 5,124
  • 1
  • 23
  • 41
  • I'm not trying to achieve anything, I'm just messing around with oo programming and learning something along the way. – 0plus1 Aug 16 '10 at 10:18
  • 1
    I don't believe you're not trying to achieve anything :) Anyhow, the meta-aspect of your question is I think well covered by @Pekka's answer. – Nicolas78 Aug 16 '10 at 10:42