# Instance

> Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [di](/docs/api/yii/di/index.md) › Instance

| class | `yii\di\Instance` |
| --- | --- |
| Since | 2.0 |
| Source | [`framework/di/Instance.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/di/Instance.php#L57) |

Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.

You may use [`get()`](/docs/api/yii/di/instance/index.md#method-get) to obtain the actual object referenced by [`$id`](/docs/api/yii/di/instance/index.md#property-id).

Instance is mainly used in two places:

- When configuring a dependency injection container, you use Instance to reference a class name, interface name
  or alias name. The reference can later be resolved into the actual object by the container.
- In classes which use service locator to obtain dependent objects.

The following example shows how to configure a DI container with Instance:

```
$container = new \yii\di\Container;
$container->set('cache', [
    'class' => 'yii\caching\DbCache',
    'db' => Instance::of('db')
]);
$container->set('db', [
    'class' => 'yii\db\Connection',
    'dsn' => 'sqlite:path/to/file.db',
]);
```

And the following example shows how a class retrieves a component from a service locator:

```
class DbCache extends Cache
{
    public $db = 'db';

    public function init()
    {
        parent::init();
        $this->db = Instance::ensure($this->db, 'yii\db\Connection');
    }
}
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-id"></span>`$id` | `string` | The component ID, class name, interface name or alias name Default: `null`. | `Instance` |
| <span id="property-optional"></span>`$optional` | `bool` | If null should be returned instead of throwing an exception Default: `null`. | `Instance` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`__construct()`](#method-__construct) protected | Constructor. | `Instance` |
| [`__set_state()`](#method-__set_state) static | Restores class state after using `var_export()`. | `Instance` |
| [`ensure()`](#method-ensure) static | Resolves the specified reference into the actual object and makes sure it is of the specified type. | `Instance` |
| [`get()`](#method-get) | Returns the actual object referenced by this Instance object. | `Instance` |
| [`of()`](#method-of) static | Creates a new Instance object. | `Instance` |

## Method details

### __construct() <span id="method-__construct"></span>

```php
protected function __construct(string $id, bool $optional = false)
```

Constructor.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$id` | `string` | The component ID |
| `$optional` | `bool` | If null should be returned instead of throwing an exception |

### __set_state() <span id="method-__set_state"></span>

```php
public static function __set_state(array $state): yii\di\Instance
```

Restores class state after using `var_export()`.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$state` | `array` |  |

**Returns**

[`Instance`](/docs/api/yii/di/instance/index.md)

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): when $state property does not contain `id` parameter

**Since**

2.0.12

**See also**

- <https://www.php.net/manual/en/function.var-export.php>

### ensure() <span id="method-ensure"></span>

```php
public static function ensure(object|string|array|static $reference, class-string<yii\di\T>|null $type = null, yii\di\ServiceLocator|yii\di\Container|null $container = null): ($type is null ? object : yii\di\T)
```

Resolves the specified reference into the actual object and makes sure it is of the specified type.

The reference may be specified as a string or an Instance object. If the former,
it will be treated as a component ID, a class/interface name or an alias, depending on the container type.

If you do not specify a container, the method will first try `Yii::$app` followed by `Yii::$container`.

For example,

```
use yii\db\Connection;

// returns Yii::$app->db
$db = Instance::ensure('db', Connection::class);
// returns an instance of Connection using the given configuration
$db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::class);
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$reference` | `object\|string\|array\|static` | An object or a reference to the desired object. You may specify a reference in terms of a component ID or an Instance object. Starting from version 2.0.2, you may also pass in a configuration array for creating the object. If the "class" value is not specified in the configuration array, it will use the value of `$type`. |
| `$type` | `class-string<yii\di\T>\|null` | The class/interface name to be checked. If null, type check will not be performed. |
| `$container` | [`ServiceLocator`](/docs/api/yii/di/servicelocator/index.md)`\|`[`Container`](/docs/api/yii/di/container/index.md)`\|null` | The container. This will be passed to [`get()`](/docs/api/yii/di/instance/index.md#method-get). |

**Returns**

`($type is null ? object : yii\di\T)`: The object referenced by the Instance, or `$reference` itself if it is an object.

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if the reference is invalid

### get() <span id="method-get"></span>

```php
public function get(yii\di\ServiceLocator|yii\di\Container|null $container = null): object|null
```

Returns the actual object referenced by this Instance object.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$container` | [`ServiceLocator`](/docs/api/yii/di/servicelocator/index.md)`\|`[`Container`](/docs/api/yii/di/container/index.md)`\|null` | The container used to locate the referenced object. If null, the method will first try `Yii::$app` then `Yii::$container`. |

**Returns**

`object|null`: The actual object referenced by this Instance object.

### of() <span id="method-of"></span>

```php
public static function of(string $id, bool $optional = false): yii\di\Instance
```

Creates a new Instance object.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$id` | `string` | The component ID |
| `$optional` | `bool` | If null should be returned instead of throwing an exception |

**Returns**

[`Instance`](/docs/api/yii/di/instance/index.md): The new Instance object.