S
S
Stanislav2017-02-25 18:38:31
Yii
Stanislav, 2017-02-25 18:38:31

Namespacs and creating a class object from a string with its name?

Basically, I have a set of classes named ServiceXX, where XX is a changing string.
I use Yii2, I prescribe the namespace of the class through use.

namespace app\modules\tracking\classes;
use app\modules\tracking\classes\ServiceFI;
***
$serviceName = 'ServiceFI';
$service = new $serviceName;

I get the error "Class 'ServiceFI' not found".
Accordingly, if we use the notation:
$serviceName = 'app\modules\tracking\classes\ServiceFI';
$service = new $serviceName;

That object is created correctly.
Is it possible to somehow force the search by the provided namespace?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
McBernar, 2017-02-25
@Stasgar

$serviceName = 'ServiceFI';
$model = 'app\\modules\\tracking\\classes\\' . $serviceName;
$service = new $model;

A
Alexander Pushkarev, 2017-02-25
@AXP-dev

Have you tried uploading files to autoload?

S
Sergey Suntsev, 2017-02-25
@GreyCrew

Habr to help you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question