ComputerUser
ComputerUser

Reputation: 4888

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?

Upvotes: 3

Views: 3277

Answers (2)

Gordon
Gordon

Reputation: 317049

Try call_user_func()

call_user_func(array($classname, 'getInstance'));
call_user_func($classname .'::getInstance'); // As of 5.2.3

In addition, if you want to build a class manager that handles arbitrary object creation for you, have a look at the Symfony Dependency Injection Components and also at this very easy to follow presentation on SlideShare about Dependency Injection with PHP in general.

Upvotes: 1

TuomasR
TuomasR

Reputation: 2316

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

Upvotes: 4

Related Questions