createObject() public static method
Creates a new object using the given configuration.
You may view this method as an enhanced version of the new
operator. The method supports creating an object based on a class name, a configuration array or an anonymous function.
Below are some usage examples:
// create an object using a class name $object = Yii::createObject('yii\db\Connection'); // create an object using a configuration array $object = Yii::createObject([ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); // create an object with two constructor parameters $object = \Yii::createObject('MyClass', [$param1, $param2]);
Using dependency injection container, this method can also identify dependent objects, instantiate them and inject them into the newly created object.
See also yii\di\Container.
public static object createObject ( $type, array $params = [] ) | ||
---|---|---|
$type | string|array|callable |
The object type. This can be specified in one of the following forms:
|
$params | array |
The constructor parameters |
return | object |
The created object |
throws | yii\base\InvalidConfigException |
if the configuration is invalid. |
Please login to continue.