E
E
eugenyh2015-05-25 15:40:42
Yii
eugenyh, 2015-05-25 15:40:42

How to create object in Yii2 by name in variable?

Previously, in Yii1, you could create models like this:

$modelName = 'MyModel';
new $modelName;

In Yii2, this does not work, since namespaces are introduced.
In the controller, I wrote:
use frontend\models\MyModel;
however
new $modelName;
, it still cannot find this model.
Obviously I'm doing something wrong. Tell me who knows.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Khomenko, 2015-05-25
@iiifx

Here Yii2 is not in business at all. This is the work with namespaces that you need to learn.

$string = '\\read\\the\\docs\\Php';
$obj1 = new  $string;

$result = $string::someMethod();

A
Alexander David, 2015-05-25
@alexdevid

same only with namespace

$modelName = '\frontend\models\MyModel';
new $modelName;

L
Lumore, 2015-05-25
@Lumore

use frontend\models\MyModel;
$modelName = new MyModel();

like so.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question