E
E
E6APB2017-08-10 23:06:10
Laravel
E6APB, 2017-08-10 23:06:10

How to include classes at runtime in PHP?

I will have dofiga of the same type of classes. Well, about 20 for sure. There will be the same methods, just their body will be different. Due to such a large number, I think using use at the beginning of the controller is impractical (or advisable?). I would like to use classes on the fly. How is it better to implement this - use at the beginning or in some other way?
This is by analogy with migrations in Laravel - almost the same classes, just the bodies of the methods are different

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Koryukov, 2017-08-11
@E6APB

As Stalker_RED already wrote , the class does not have to be used. You can simply address him by his full name. The full class name is namespace + class name.
Because If you create a class object based on some data, then sooner or later it will come down to writing the full class name as a string into a variable and then using this variable to create an object.

function makeObject($class_name){
    $full_class_name = "\\app\\some_strategy\\" . $class_name;
    return new $full_class_name();
}

In addition, Melkij mentioned a design pattern that is used just to encapsulate the logic of creating an object based on some data. Depending on the subject area, and how the creation of such objects fits into it, it makes sense to consider such patterns as Factory Method and Abstract Factory.

M
Melkij, 2017-08-10
@melkij

Since they are of the same type, then maybe they solve the same type of problem?
Maybe you need the factory pattern in the controller as well, and will only use the factory?

S
Stalker_RED, 2017-08-10
@Stalker_RED

www.php-fig.org/psr/psr-4

// эти две строчки подключают точно такой-же класс
use ProjectName\Admin\User as User; 
$user = new User();

// как эта строчка
$user = ProjectName\Admin\User();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question