Search code examples
phpsingletonclassloader

Using a variable to dynamically load a class


I have decided to use the singleton pattern for my application. It makes the most sense to me. However, just when I feel like I have made some progress I run into another wall.

I have a load function. The load function does the following.

Check if class has been previously loaded. - If so - return $class::get_instance(); - Otherwise - look for class in various places - if found - return $class::get_instance(); - else return error.

Before adopting the Singleton pattern I was instantiating classes with the load class.

In the controller I would have this.

$session = $this->load->library('session');

The load class would then find the file and return..

return new $class_name;

I hoped that the in changing the method of loading classes it would be a tweak to a few lines but these tweaks are generating syntax errors.

return $class_name::get_instance();

Is there a way to write the line above without the syntax error?


Solution

  • How about using call_user_func?

    return call_user_func(array($class_name, "get_instance"));
    

    http://www.php.net/manual/en/function.call-user-func.php