createObject() public static method

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: php 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 [[\yii\di\Container|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 createObject ( string | array | callable $type, array $params = [] ) : object
$type string | array | callable the object type. This can be specified in one of the following forms: - a string: representing the class name of the object to be created - a configuration array: the array must contain a `class` element which is treated as the object class, and the rest of the name-value pairs will be used to initialize the corresponding object properties - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`). The callable should return a new instance of the object being created.
$params array the constructor parameters
return object the created object
Beispiel #1
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     if (!$this->apiKey) {
         throw new InvalidConfigException('"' . get_class($this) . '::apiKey" must be set.');
     }
     if (!is_string($this->apiKey)) {
         throw new InvalidConfigException('"' . get_class($this) . '::apiKey" must be a string, ' . gettype($this->apiKey) . ' given.');
     }
     $this->sparkpostConfig['key'] = $this->apiKey;
     // Initialize the http adapter, cUrl adapter is default
     $adapterConfig = new Configuration();
     $adapterConfig->setTimeout(4);
     $httpAdapter = $this->httpAdapter ? BaseYii::createObject($this->httpAdapter) : new CurlHttpAdapter($adapterConfig);
     $this->_sparkPost = new SparkPost($httpAdapter, $this->sparkpostConfig);
     if ($this->useDefaultEmail && !$this->defaultEmail) {
         if (!isset(\Yii::$app->params['adminEmail'])) {
             throw new InvalidConfigException('You must set "' . get_class($this) . '::defaultEmail" or have "adminEmail" key in application params or disable  "' . get_class($this) . '::useDefaultEmail"');
         }
         $this->defaultEmail = \Yii::$app->name . '<' . \Yii::$app->params['adminEmail'] . '>';
     }
 }