views:

16

answers:

1

Here is the basics of my framework:

class CPU {

    public function load_class($class) {
        include_once($class . ".php");
        $this->$class = new $class;
    }

    public function load_controller($class) {
        include_once($class . ".php");
        $class = new $class;
        $class->index();
    }

    public function run() {

        // Load DB class
        $this->load_class("DB");

        // Load controller
        $this->load_controller("About");
    }
}

class About extends CPU {
    public function index() {
        $this->DB->connect();
    }
}

When run() is called to load the About class, accessing $DB gives the error below:

Fatal error: Call to a member function connect() on a non-object

I assume I need to use a singleton to create the class dynamically. CodeIgniter works in the same way but I can't work out what I have to do to amend my framework to make this work?

A: 

I suggest using __autoload() or spl_autoload_register() to load your classes instead hard coding the include().

About your problem, the "About" class does not ever instantiate a member of DB. Its parent, CPU, has no DB member either. In other words, you probably want DB to be a member of CPU or About. It is hard to say without knowing what you are trying to do.

Even if you did make DB a member of either, you would still have to add it to the instance of the About class that is instantiated in load_controller().

In other words it seems like you are really just doing this wrong. That DB has no connection to About at all. It is hard to give you more help without knowing exactly what you are trying to do.

About using a Singleton, that has nothing to do with anything. A Singleton is just a class that you only ever need one of. They are frequently overused and misused. Use with caution!

tandu