Using a variable to dynamically load a class

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

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

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

Before using the Singleton template, I created classes with a load class.

In the controller, I would do that.

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

Then the load class will find the file and return.

return new $class_name;

I was hoping that when changing the method of loading classes, this will be a setting for several lines, but these settings generate syntax errors.

return $class_name::get_instance();

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

+3
source share
2 answers

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

+4
source

Try call_user_func()

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

Also, if you want to create a class manager that handles arbitrary object creation, look at the Symfony Dependency injection components and it’s also very easy to follow the presentation on SlideShare about dependency injection with PHP in general.

+1
source

Source: https://habr.com/ru/post/1728598/


All Articles